What is the correct and safest way to memset the whole character array with the null terminating character? I can list a few usages:
...
char* buffer = new char [ARRAY_LENGTH];
//Option 1: memset( buffer, '\0', sizeof(buffer) );
//Option 2 before edit: memset( buffer, '\0', sizeof(char*) * ARRAY_LENGTH );
//Option 2 after edit: memset( buffer, '\0', sizeof(char) * ARRAY_LENGTH );
//Option 3: 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.