How to memset char array with null terminating character?
The idiomatic way is value-initializing the array:
char* buffer = new char [ARRAY_LENGTH]();
Option 1 only sets the first sizeof(char*)
bytes to 0, or runs into undefined behavior if ARRAY_LENGTH < sizeof(char*)
. This is due to using the size of the pointer instead of the size of the type.
Option 2 runs into undefined behavior because you're attempting to set more than ARRAY_LENGTH bytes. sizeof(char*)
is almost certainly greater than 1.
Since this is C++ though (no new
in C), I suggest you use a std::string
instead.
For C (assuming malloc
instead of new[]
), you can use
memset( buffer, 0, ARRAY_LENGTH );
Options one and two are just wrong. The first one uses the size of a pointer instead of the size of the array, so it probably won't write to the whole array. The second uses sizeof(char*)
instead of sizeof(char)
so it will write past the end of the array. Option 3 is okay. You could also use this
memset( buffer, '\0', sizeof(char)*ARRAY_LENGTH );
but sizeof(char)
is guaranteed to be 1.