VS2022报 “Debug Error! HEAP CORRUPTION DETECTED: after Normal block (#82) at 0x000001C1B26B0860” 错误
问题:
运行VS2022,出现Error! HEAP CORRUPTION DETECTED: after Normal block (#82)
at 0x000001C1B26B0860错误
原因:
这个错误的意思就是错误!检测到堆损坏:在正常块(#82)之后,CRT监测到应用程序在堆缓冲区结束后写到内存,按Retry调试应用程序。
说白话,这个错误的原因就是使用的内存未完全释放,造成实际使用的内存大小超过了你申请的内存大小。
错误代码:
如下代码运行后,就会报出上述错误
#include<stdio.h>
#include<stdlib.h>
#include<errno.h>
int main()
{
int n;
while (scanf("%d", &n) != EOF)
{
int* p = (int*)malloc(n * sizeof(int));
if (NULL == p)
printf("%s\n", errno);
else {
for (int i = 0; i < n; i++)
{
*(p + i) = i;
printf("%d ", *(p + i));
}
printf("\n");
free(p);
}
}
return 0;
}
代码运行后,虽然有个free函数进行了动态内存的释放与回收,但实际中未完全释放,p依然指向动态开辟的空间,而非指向NULL。当第一次使用完40个空间后,如果未退出,继续运行代码,再次赋值就会发生错误。要想避免错误,只需在free函数前把p进行赋值NULL操作即可。
正确代码:
int main()
{
int n;
while (scanf("%d", &n) != EOF)
{
int* p = (int*)malloc(n * sizeof(int));
if (NULL == p)
printf("%s\n", errno);
else {
for (int i = 0; i < n; i++)
{
*(p + i) = i;
printf("%d ", *(p + i));
}
printf("\n");
p = NULL;
free(p);
}
}
return 0;
}