Interview Question
Country: United States
And why memory on stack can`t be freed by operator delete()? What exactly causes an assertion?
I believe delete only releases memory that has been allocated using new operator.
Just for the sake of it , I tried using delete operator on memory allocated on stack, that has caused my program to crash on Ubuntu and WindowsXP. I don't know if any other OS has a different behavior. Thanks
VC++ crashes on assert(), trying to get some header from deleting pointer. This header may include the size of deleting object (or the size of array).
__________________________
| header | dynamically |
|________| allocated data__|
^
|
operator delete() tryes to get this info (it is there for heap object), but can`t.
when you allocate memory using new ; this process also inserts some data such as number of bytes that were allocated.where exactly this bookkeeping will be stored is totally implementation specific.But when you delete the operator looks for that bookkeeping information in order to determine how many bytes to free.probably "looking for this bookkeeping" information is what causes seg fault
This would cause _BLOCK_TYPE_IS_VALID assertion. This is the error compiler would throw when user is trying to call delete when memory hasn't been allocated.
/* get a pointer to memory block header */
pHead = pHdr(pUserData);
/* verify block type */
_ASSERTE(_BLOCK_TYPE_IS_VALID(pHead->nBlockUse));
_free_dbg( pUserData, pHead->nBlockUse );
The memory for the array is not dynamically allocated. It is not defined what happens, when you free memory that was not allocated by new previously. The C++ example below works fine.
- thomas November 24, 2010