Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ delete array crashes

Tags:

c++

This is my code...

int* getA(int no)
{
   int *a = new int[no];
   return a;
}

void main()
{
   int* a = getA(10);
   delete []a;
}

When I delete the array a in main it crashes... what is the reason??

The error is "Windows has triggered a breakpoint in Final.exe. This may be due to a corruption of the heap, which indicates a bug in Final.exe or any of the DLLs it has loaded..........." But I am able to assign and access the elements of a in the main method but when I try to delete it is crashing....

like image 292
user570593 Avatar asked Apr 07 '26 02:04

user570593


2 Answers

Nothing wrong with this code. Presumably either

  1. It differs from your real code in some significant way, or
  2. Something unrelated in your real code is corrupting the heap before this code runs.
like image 142
Ernest Friedman-Hill Avatar answered Apr 08 '26 14:04

Ernest Friedman-Hill


It should just work (the delete).

Possibly, the application crashes because of undefined behaviour, if your compiler accepted that code. Try the following, and run it under a debugger to verify that it crashes in the delete:

int* getA(int no)
{
   int *a = new int[no];
   return a;
}

int main()
{
  int* a = getA(10);
  delete []a;

  return 0;
}
like image 24
sehe Avatar answered Apr 08 '26 15:04

sehe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!