-
-
Notifications
You must be signed in to change notification settings - Fork 740
Description
Passing in a string
to tempCString
that has internal NUL characters will not return an equivalent C string. In fact, a C string cannot represent such a string.
But tempCString
is always copying the data. So we have an opportunity to check for these nested NUL characters. The key is not to make it slow (memcpy is fast).
To that end, we should replace the slice assign to strncpy
From the strncpy
docs:
char * strncpy ( char * destination, const char * source, size_t num );
Copies the first num characters of source to destination. If the end of the source C string (which is signaled by a null-character) is found before num characters have been copied, destination is padded with zeros until a total of num characters have been written to it.
No null-character is implicitly appended at the end of destination if source is longer than num. Thus, in this case, destination shall not be considered a null terminated C string (reading it as such would overflow).
If we use strncpy
, we can check afterwards the final character, and if it's not NUL, we can assume no NUL characters were found. Otherwise, we can indicate this in a field inside the tempCString
structure.