3

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....

4
  • 1
    Could you provide some error message? Commented Sep 30, 2011 at 14:53
  • 2
    It does not crash for me. Also, this main() definition is not legal in C++. Commented Sep 30, 2011 at 14:53
  • 2
    This shouldn't crash. Is this the code you're actually using? Commented Sep 30, 2011 at 14:57
  • void main() is a compiler extension. It should be int main(), even if you don't return anything. Commented Sep 30, 2011 at 15:18

2 Answers 2

3

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.
Sign up to request clarification or add additional context in comments.

Comments

1

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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.