3 ms·
strncpy notoriously doesn't necessarily 0-terminate. (It also always pads the full length with zeroes if necessary, so it's almost never what you actually want
by naniwaduni 7y ago
strncpy notoriously doesn't necessarily 0-terminate.
(It also always pads the full length with zeroes if necessary, so it's almost never what you actually want to do.)
The C standard library is full of these footguns.
I won't say C++ doesn't have its bad parts, and I certainly wouldn't say that it's impossible to avoid the bad parts of C (some would), but you probably aren't going to manage.
- scarface74 7y agoIf all of your string manipulation is working with the knowledge of the maximum size, how is that any different than the standard Pascal or BSTR string handling where the size of the string can be found in the first two bytes of the string? The typical error case with C is something like char *a = “abcd”; //5 bytes char *b = “efgh”; char c[8]; strcpy(c,a); strcat(c,b); //buffer overflow by 1 byte. If you used the “n” equivalents, c would have 8 bytes and every other function would know to stop 8 bytes - assuming you always pass in a size parameter.
- AnimalMuppet 7y agoThat might work - if you always use that pattern, and never, never deviate from it, including in all library functions that you ever call with your strings. That seems very brittle and error prone, though. And why, when you have C++ strings that just handle all of that for you?
- naniwaduni 7y agoIt's not. But plenty of other standard C functions like to use 0-terminated strings without explicit lengths, including most of the system interfaces, and others make it awkward to pass in the length that you're actually tracking. You only need to call one of those with an unterminated string and it doesn't even matter whether your code knows the string's length. You could say that just means you have to be very careful whenever you pass a pointer to a string around without also passing in its length, but that's a lot of places.