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

时间:2023-03-08 20:22:02
CRT detected that the application wrote to memory after end of heap buffer.

很多人的解释都不一样,  我碰到的问题是,开辟的内存空间小于操作的内存空间.也就是说,我free的内存越界了.

这是我开辟链表结构体内存的代码:

 PNODE Create() {
int len; //total count of nodes to be created.
int i;
int val; //temp value for the current node.
printf("enter the size of nodes:");
scanf("%d", &len);
PNODE pHead = (PNODE)malloc(sizeof(PNODE));
pHead->pNext = NULL;
PNODE pTail = pHead; if(NULL == pHead) {
printf("allocate memory failed!");
exit();
}
for (i = ; i < len; i++)
{
PNODE pCur = (PNODE)malloc(sizeof(PNODE));
if(NULL == pCur) {
printf("allocate memory failed!");
exit();
}
printf("enter the %d-th value : ", i + );
scanf("%d", &val);
pCur->data = val; //set the new node as the tail node.
pTail->pNext = pCur;
pCur->pNext = NULL;
pTail = pCur;
}
return pHead;
}

我是这样定义结构体的:

 typedef struct node {
int data;
struct node * pNext;
} NODE, * PNODE;

删除元素时(报错的代码)为:

 bool Delete(PNODE pHead, int pos, int *v) {
int i = -;
PNODE pNode = pHead;
while((i < pos - ) && pNode != NULL) {
pNode = pNode->pNext;
i++;
}
if(pos < i || pNode == NULL)
return false;
PNODE pTmp = pNode->pNext; //store to free later.
*v = pTmp->data;
pNode->pNext = pNode->pNext->pNext;
free(pTmp);
pTmp = NULL;
return true;
}

  这段代码我翻来覆去地调试,发现所有的节点的指针域和数据域都是我期待的.就是在free的时候报了错.

原来是我开辟内存的时候,大小指定错了,应该把:

 PNODE pNew = (PNODE)malloc(sizeof(PNODE));

改为:

 PNODE pNew = (PNODE)malloc(sizeof(NODE));

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