Search code examples
c++arrayschargarbage

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


Solution

  • 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.