Allocate room for null terminating character when copying strings in C?

c++, c-strings

Solution

You are correct that you are not allocating space for the terminator, however the failure to do this will not necessarily cause your program to fail. You may be overwriting following information on the heap, or your heap manager will be rounding up allocation size to a multiple of 16 bytes or something, so you won't necessarily see any visible effect of this bug.

If you run your program under Valgrind or other heap debugger, you may be able to detect this problem sooner.

Problem

const char* src = "hello"; Calling `strlen(src);` returns size 5... Now say I do this: ``` char* dest = new char[strlen(src)]; strcpy(dest, src); ``` That doesn't seem like it should work, but when I output everything it looks right. It seems like I'm not allocating space for the null terminator on the end... is this right? Thanks

Original source