Search code examples
c++pointersdynamic-memory-allocationdelete-operator

Why does my program crash when I increment a pointer and then delete it?


I was solving some programming exercise when I realised that I have a big misunderstanding about pointers. Please could someone explain the reason that this code causes a crash in C++.

#include <iostream>

int main()
{
    int* someInts = new int[5];

    someInts[0] = 1; 
    someInts[1] = 1;

    std::cout << *someInts;
    someInts++; //This line causes program to crash 

    delete[] someInts;
    return 0;
}

P.S I am aware that there is no reason to use "new" here, I am just making the example as small as possible.


Solution

  • It's actually the statement after the one you mark as causing the program to crash that causes the program to crash!

    You must pass the same pointer to delete[] as you get back from new[].

    Otherwise the behaviour of the program is undefined.