2

This is really weird. If I increase the value of asize just by one crashSystem() does what its name speaks. Second function returning an int pointer works ok with much bigger values. Those two functions just delete and allocate the same dynamic array with same size (I created it just for test purposes).

Note: I think it could have something to do with maximum stack capacity 1MB (130037 * 8 in bytes is near 1MB), but it's really strange 'cause allocating using new inside function should work the same as any other new.

Using Visual Studio 2015

#include <iostream>

void crashSystem(int * dynamicArray, int asize) {
    delete[] dynamicArray;
    //dynamicArray = nullptr; does not matter at all
    dynamicArray = new int[asize];
    std::cout << "mem allocated\n";
}

int * worksOk(int * dynamicArray, int asize) {
    int * newDynamicArray = new int[asize];
    delete[] dynamicArray;
    std::cout << "mem allocated\n";
    return newDynamicArray;
}

int main()
{
    int asize = 130037; // dynamic array size
    //asize = 12330037; // for testing second function that works
    int * dynamicArray;

    dynamicArray = new int[asize];

    for (int i = 0; i < 100; i++)
    {
        std::cout << "iteration " << i << " ";
        crashSystem(dynamicArray, asize);
        //dynamicArray = worksOk(dynamicArray, asize);
    }
    std::cout << "\n";
    system("PAUSE");
}

Note 2: Crashing app this way in Release mode tends to block executable by creating non existent process (checked with Process Hacker 2)

LogicStuff
  • 18,687
  • 6
  • 49
  • 70
Shabrido
  • 79
  • 1
  • 6

1 Answers1

6

The problem is that you're passing pointer by value, so it still points to the new int[asize]; allocated in main(), on which you then call multiple delete []. It becomes a dangling pointer after the first delete [] call.

Even assigning nullptr won't help you if the pointer is not being passed by reference.

worksOk works, because you're returning the pointer pointing to the newly allocated space and assigning it, so it's valid every time.

Just change the signature so it uses reference:

void crashSystem(int *&dynamicArray, int asize)

and it should work fine.

Community
  • 1
  • 1
LogicStuff
  • 18,687
  • 6
  • 49
  • 70