[Transfer] HEAP CORRUPTION DETECTED: after Normal block error solution

One: Problem description:

The problems that arise are as follows:

 

2: Explanation of the cause of the problem

  This problem occurs when manipulating heap memory. The reason for this problem is that the memory size you actually use exceeds the memory size you actually requested, and this problem will occur when the memory is released.

  For example: If you apply for 3 bytes of heap memory space char *ptr = (char *)malloc(sizeof(char)*3);

                    But you used 4 bytes when using, char *t1 = "abc";// Note that there is a '\0' character at the end

                                                                               strcpy(ptr, buf);// The copy function will add a '\0' character at the end by default, here you only apply for 3 bytes of space, but the space you actually use is 4 bytes

                      When more than one byte of content is written into the 3-byte heap memory space pointed to by ptr, the compiler in vs2010 will not report an error, but it will lay a huge hidden danger for the subsequent memory release.

                     After that, when you release the memory pointed to by ptr, because you use more than the requested memory space, the memory cannot be released correctly, and the above problem will occur.

Three: Example

The code in question is as follows:

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std;
int main()
{
    const char* t1 = "abc";
    cout << sizeof(t1) << endl; // 4

    // 申请内
    int memSize = 3;
    char* ptr = (char*)malloc(sizeof(char) * memSize);  // 仅仅申请了3个字节的堆内存空间
    // 初始化内存
    memset(ptr, 0, memSize);
    // 拷贝内容
    strcpy(ptr, t1);  // strcpy拷贝时末尾默认会添加一个'\0'字符, 所以实际使用的内存空间为4个字节,超出了申请的内存空间大小,为后来的内存释放埋下了巨大的隐患

    cout << ptr << endl;

    if (ptr != NULL)
    {
        free(ptr);
        ptr = NULL;
    }

    system("pause");
    return 0;
}

After running the above code, the following problem will appear

Correct code:

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std;
int main()
{
    const char* t1 = "abc";
    cout << sizeof(t1) << endl; // 4

    // 申请内
    //int memSize = 3;// 申请内存的大小必须与实际使用的内存大小一致
    int memSize = 4;// 实际使用的内存大小为4个字节,那么申请内存必须大于等于实际使用的内存。
    char* ptr = (char*)malloc(sizeof(char) * memSize);
    // 初始化内存
    memset(ptr, 0, memSize);
    // 拷贝内容
    strcpy(ptr, t1);

    cout << ptr << endl;

    if (ptr != NULL)
    {
        free(ptr);
        ptr = NULL;
    }

    system("pause");
    return 0;
}

Four: Summary

When the actual memory size used exceeds the requested memory space, a HEAP CORRUPTION DETECTED:after Normal block error will be triggered when the memory is released later.

Solution: When applying for heap memory space, the size of the requested space must be greater than or equal to the size of the actually used memory space.

 

Guess you like

Origin blog.csdn.net/laolitou_1024/article/details/125740381