1

Why it has error in releasing the static array in debug mode?

int main()
{
 int ar[] = { 1,2,3,4,5,6,7,8,9 };
 //other code

 delete(ar);
 // or free(ar);

 return 0;
}

I used free or delete to release the array and it finished with error in debug mode.
Do i use the free or delete correctly?
How can i release the array?

SaeidMo7
  • 1,214
  • 15
  • 22

2 Answers2

3

ar[] is not allocated on the heap, but local/on the stack, so can't be (and shouldn't be) deleted.

The memory is released on function (or block {}) exit.

You can only use delete with new or free() with malloc()

Danny_ds
  • 11,201
  • 1
  • 24
  • 46
2

the delete operator and 'free' function are to be used only on pointers that own memory allocated on the heap. your array is allocated on the stack, and the internal implementation will crash when it will not find any heap structure.

moreover, delete is only to be applied on memory allocated with new and free only on memory allocated with malloc,calloc or realloc.

last thing is that when you use delete on an array, use delete [] for this means that the removal will take place on an earlier offset on the stack, when the record of the array itself is allocated, doing otherwise might end with a memory leak or worse

Or Yaniv
  • 571
  • 4
  • 11