CRT detected that the application wrote to memory after end of heap buffer.

來源:互聯網
上載者:User

標籤: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));

開闢節點的大小應該為結構體的大小,其實我在‘插入‘新節點的時候,這行代碼就寫錯了,但是不會報錯.我覺得應該是沒有釋放.

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.