c++memorymemory-managementheap-memoryheap-corruption

Heap Corruption happening while delete[] for partially allocated array


I had a heap corruption error recently which I solved but cannot understand what is happening

I am allocating memory for a DBL array,

new DBL[length+1]; // where length = 1000;

Later I am writing more than 1000 elements to this array. There was no error at the time of memory allocation and processing this data. Later before adding new values to this array, I called delete[] on this and then it is giving me Heap corruption error.

Since I had 1000 blocks allocated to the array I was expecting it to delete it smoothly or definitely give an exception when I am trying to write to the blocks. Not while deleting. I know it is undefined behaviour in C++. But can someone help me understand this or have an explanation?


Solution

  • Reproducing your question in code example:

    struct DBL
    {
        int x{};
    };
    
    
    int main()
    {
        const int length{1000}; // increase this to get segfault before "for" loop ends
        DBL* arr = new DBL[length+1];    
        for (int i = 0; i < 3*length; i++)
        {
            arr[i].x = i;  // UB here since i > length
        }
        delete[] arr;  // not necessarily reached
        return 0;
    }
    

    Once you're out of bounds of allocated memory, you have Undefined Behaviour (https://en.cppreference.com/w/cpp/language/ub). The results can depend on your machine, compiler and its options, OS, and many other things.

    Even the size of the array can matter. For example, if you increase your array size from 1000 to, say, 100000, you'll likely get Segmentation Fault even if you comment out your delete[]. And you'll likely get it before you reach the end of the loop over 3*length iterations.

    It doesn't explain the reasons why. It illustrates that the reason is not in delete[].