Deleting a char array


Question

This question is related to this one. Given this code:

char *p = new char[200];
delete[] p;

what would happen if you set p[100] = '\0' before deleting p?

I had some code where I got a debug error when I tried to delete a not null-terminated char array, something about deleting heap memory that's not assigned. It seemed to delete memory out of the array's bounds.

1
23
7/29/2017 7:26:59 PM

Accepted Answer

The code:

char *p = new char[200];
p[100] = '\0';
delete[] p;

is perfectly valid C++. delete does not know or care about null-terminated strings, so your error must have had some other cause.

41
4/18/2009 2:34:13 PM

Nothing special would happen. You would write at some place in the middle of the allocated memory (100 bytes apart from the start, 99 bytes before the end of the allocated memory).

Then you would free that allocated memory. The compiler will handle it exactly as we would expect. The memory allocated by that is completely unrelated to null terminated strings. You could stick everything you want into that memory. It's some "raw" chunk of storage, you could even create some arbitrary C++ object into that memory (placement new).

Your bug is somewhere else. For example, some common error is this one, where the constructor is called once, but the destructor is called twice, double-deleting something:

struct A { P *p; A() { p = new P; } ~A() { delete p; } };
A getA() { return A(); } int main() { A a = getA(); }

Now, what happens is that the default constructor is called once, and the created object is copied zero or more times. But the destructor is run for each copy that's created. Thus, you will call the destructor on the pointer more than once, leading to such strange bugs. The correct way to fix that is to use a smart pointer, like shared_ptr. As an exercise, you can also do it without, by writing proper copy constructors that copy the object over and allocate memory in the copy constructor, so that the copy and the respective original object keep distinct pointers.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon