user1112008
user1112008

Reputation: 442

Playing with char array

Is that safe to do something like this:

char* charArray = new char[10];  
strcat(charArray, "qwertyuiop");  
charArray[3] = '\0';  
delete [] charArray;

Will everything be deleted? Or that what is after \0 won't be? I don't know if I'm leaving garbage.

EDIT: should be strcpy

Upvotes: 1

Views: 1337

Answers (5)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

Apart from the fact that new[] for POD-types does not zero-initializes the array, and strcat would write the terminating '\0' past the end of the allocated area, everything looks fine: in particular, delete will delete the entire block.

The reason for writing past the end of the allocated block is that the 10-character string "qwertyuiop" requires 11 bytes to store.

Upvotes: 7

Mat
Mat

Reputation: 206669

No, this is fine, the whole array is deleted. delete doesn't look at what the pointer you give it points to. As long as you match new with delete, and new[] with delete[], the right amount of memory will be freed.

(But do consider using std::string instead of char arrays, that'll avoid a lot of bugs like the one you have there writing past the end of your array.)

Upvotes: 2

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361252

If you wanted to write strcpy instead of strcat, then that is safe and correct. But it seems you've a misconception about delete [] charArray. It doesn't delete characters, it deletes the memory pointed to by charArray. The memory even after delete [] charArray might contain those characters, it is not guaranteed though.

However, if you really wanted to write strcat, and it is not a typo, then your code invokes undefined behavior, because charArray contains garbage to which strcat will attempt to concatenate the second string.

Upvotes: 5

Dietmar Kühl
Dietmar Kühl

Reputation: 153792

The delete[] releases the memory allocated after destroying the objects within (which diesn't do anything for char). It doesn't care about the content i.e. it will deallocate as many objects as were allocated.

Note that the use of strcat() depends on a null character to find the end of the string and that the memory returned from new char[n] is uninitialized. You want to start of with

*charArray = 0;

... and you might want to consider strncat() or, yet better, not use this at all but rather use std::string.

Upvotes: 3

Jeremiah Willcock
Jeremiah Willcock

Reputation: 30969

The delete[] statement does not know anything about what is stored in the buffer (including whether it is a string or not), so it will delete all 10 characters. However, your strcat call is overflowing the end of the array (since C strings have a zero byte as terminator), which might break deletion on your platform and is not safe in general.

Upvotes: 2

Related Questions