Home > Blockchain >  free: invalid pointer when deleting a dynamically created array
free: invalid pointer when deleting a dynamically created array

Time:09-17

I'm currently practicing pointers arithmetics and I can't figure out why this code ends on a "free(): invalid pointer" error when it comes to executing the last line with delete [] arr;.

I realized that the same code runs without any issue when using the program C4Droid on my Android phone (using the compiler "G Bionic") but on my tablet using GCC, it just doesn't work. The only way I found around it is to make sure that the arr array is currently pointing to the first address. The moment it doesn't it seems to fail. I don't know if it SHOULD fail on my phone too or if it's somehow a configuration issue in the IDE I use on my tablet (tried with codeblocks and codelite). Can you please help?

I'm also well aware that I'm initializing values for the two first spots of the array while it's technically possible to choose an array size smaller than this. It's just tests.

#include <string>
#include <iostream>

int main()
{
    int *arr{};
    size_t size{};
    std::cout << "Please enter the size of the array you want to create: "; std::cin >> size;
    arr = new int[size];
    *(arr   0) = 5;
    *(arr   1) = 10;
    std::cout << "  arr: " <<   arr << " (pointer incrementation, we move by an int and arr is now arr   1)" << std::endl;  
    delete [] arr;
    return 0;
}

CodePudding user response:

You aren't deleting the same pointer you allocated - arr moved the pointer. Calling delete[] on any pointer that wasn't allocated by new type[] is undefined behavior - it could work, it could fail catastrophically and it could do anything in between - but you really should not rely on it.

CodePudding user response:

After this statement where you incremented the pointer arr

std::cout << "  arr: " <<   arr << " (pointer incrementation, we move by an int and arr is now arr   1)" << std::endl;  

the pointer now does not have the address of the allocated memory.

So the next statement

delete [] arr;

invokes undefined behavior.

You have to pass to the operator delete [] a pointer with the same value (address) that was returned by the operator new.

You could write for example

delete [] --arr;

using the decrement operator to reset the pointer to its initial value.

  • Related