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 );
...
- Does any of these have significant advantage over other(s)?
- What kind of issues can I face with with usages 1, 2 or 3?
- What is the best way to handle this request?
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 ofsizeof(char)so it will write past the end of the array. Option 3 is okay. You could also use thisbut
sizeof(char)is guaranteed to be 1.