標籤:des style blog color os 資料
很多人的解釋都不一樣, 我碰到的問題是,開闢的記憶體空間小於操作的記憶體空間.也就是說,我free的記憶體越界了.
這是我開闢鏈表結構體記憶體的代碼:
1 PNODE Create() { 2 int len; //total count of nodes to be created. 3 int i; 4 int val; //temp value for the current node. 5 printf("enter the size of nodes:"); 6 scanf("%d", &len); 7 PNODE pHead = (PNODE)malloc(sizeof(PNODE)); 8 pHead->pNext = NULL; 9 PNODE pTail = pHead;10 11 if(NULL == pHead) {12 printf("allocate memory failed!");13 exit(0);14 }15 for (i = 0; i < len; i++)16 {17 PNODE pCur = (PNODE)malloc(sizeof(PNODE));18 if(NULL == pCur) {19 printf("allocate memory failed!");20 exit(0);21 }22 printf("enter the %d-th value : ", i + 1);23 scanf("%d", &val);24 pCur->data = val;25 26 //set the new node as the tail node.27 pTail->pNext = pCur; 28 pCur->pNext = NULL;29 pTail = pCur;30 }31 return pHead;32 }
我是這樣定義結構體的:
1 typedef struct node {2 int data;3 struct node * pNext;4 } NODE, * PNODE;
刪除元素時(報錯的代碼)為:
1 bool Delete(PNODE pHead, int pos, int *v) { 2 int i = -1; 3 PNODE pNode = pHead; 4 while((i < pos - 1) && pNode != NULL) { 5 pNode = pNode->pNext; 6 i++; 7 } 8 if(pos < i || pNode == NULL) 9 return false;10 PNODE pTmp = pNode->pNext; //store to free later.11 *v = pTmp->data;12 pNode->pNext = pNode->pNext->pNext;13 free(pTmp);14 pTmp = NULL;15 return true;16 }
這段代碼我翻來覆去地調試,發現所有的節點的指標域和資料域都是我期待的.就是在free的時候報了錯.
原來是我開闢記憶體的時候,大小指定錯了,應該把:
1 PNODE pNew = (PNODE)malloc(sizeof(PNODE));
改為:
1 PNODE pNew = (PNODE)malloc(sizeof(NODE));
開闢節點的大小應該為結構體的大小,其實我在‘插入‘新節點的時候,這行代碼就寫錯了,但是不會報錯.我覺得應該是沒有釋放.