I came across an article on new
/ operator new
:
The many faces of operator new in C++
I couldn't understand the following example:
int main(int argc, const char* argv[])
{
char mem[sizeof(int)];
int* iptr2 = new (mem) int;
delete iptr2; // Whoops, segmentation fault!
return 0;
}
Here, the memory for int
wasn't allocated using new
, hence the segfault for delete
.
What exactly does delete
not like here? Is there some additional structure hidden when an object is initialized with new
, that delete
looks for?
EDIT: I'll take out of comments several responses which helped me to understand the situation better:
As @463035818_is_not_a_number and @HolyBlackCat pointed out,
mem
was allocated on the stack, whiledelete
tries to free memory on the heap. It's a pretty clear cut error and should lead to a segfault on most architectures.If
mem
was allocated on the heap without an appropriatenew
:
The only way to do it I know would be, say, to allocate an int*
on a heap, then reinterpret_cast
it to an array of chars and give delete
a char pointer. On a couple of architectures I tried this on, it actually works, but leads to a memory leak. In general, the C++ standard makes no guarantees in this case, because doing so would make binding assumption on the underlying architecture.