Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c-strings

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

like image 256
Polaris878 Avatar asked Nov 27 '22 23:11

Polaris878


2 Answers

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.

like image 88
Greg Hewgill Avatar answered May 01 '23 15:05

Greg Hewgill


Yes, you should allocate at least strlen(src)+1 characters.

like image 45
Juliano Avatar answered May 01 '23 16:05

Juliano