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

很多人的解释都不一样,  我碰到的问题是,开辟的内存空间小于操作的内存空间.也就是说,我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));

开辟节点的大小应该为结构体的大小,其实我在'插入'新节点的时候,这行代码就写错了,但是不会报错.我觉得应该是没有释放.

你可能感兴趣的:(application)