授人以渔,不授人以鱼。
回复 20楼 有容就大
以后可以找些open source的malloc分析分析,可能一下子没法全看懂,慢慢来,先把指针弄明白了,你还是有潜力的,相信自己至少你问的这个问题,自己可以完全靠调试弄明白,碰到这种问题,尽量把代码缩小,减小到几句,调一调就出来了
比如说一个申请,一个释放,连续2个申请,连续两个释放,代码不长,一定要自己耐心调一调
// crt_malloc.c // This program allocates memory with // malloc, then frees the memory with free. #include <stdlib.h> // For _MAX_PATH definition #include <stdio.h> #include <malloc.h> int main( void ) { char *string; // Allocate space for a path name string = malloc( _MAX_PATH ); // In a C++ file, explicitly cast malloc's return. For example, // string = (char *)malloc( _MAX_PATH ); if( string == NULL ) printf( "Insufficient memory available\n" ); else { printf( "Memory space allocated for path name\n" ); free( string ); printf( "Memory freed\n" ); } }
#include <stdio.h> #include <stdlib.h> typedef struct LNode { struct LNode *next; int num; float fl; double du; }LNode, *LinkList; LNode* ApplyMem(LNode *head) { LNode *p; int i, j; i = sizeof(LinkList); j = sizeof(LNode); printf("%d %d\n", i, j); //输出的是i, j if (NULL == head) { head = (LNode *)malloc(1 * sizeof(LinkList)); if (!head) { printf("Apply fail!\n"); return NULL; } } head->next = NULL; head->num = 1; //head->ch = 'a'; head->fl = 1.2; head->du = 22.0; p = (LNode *)malloc(1 * sizeof(LinkList)); if (!p) { printf("Apply fail!\n"); return NULL; } p->num = 2; //p->ch = 'b'; p->fl = 2.4; p->du = 54.0435; p->next = head->next; head->next = p; return head; } void FreeMem(LNode *head) { LNode *p; while (NULL != head) { p = head; head = head->next; free(p); } } void PrintList(LinkList head) { LinkList p; p = head; while (NULL != p) { printf("%d %f %f", p->num, p->fl, p->du); p = p->next; } } int main(void) { LNode *head = NULL; head = ApplyMem(head); PrintList(head); //free(head); head = NULL; return 0; }实验时先不释放。