4 ms·
What vulnerabilities does C introduce that C++ doesn't?
by rkachowski 7y ago
What vulnerabilities does C introduce that C++ doesn't?
- millstone 7y agoFor example it is easier to avoid buffer overflows with std::string than with C-style strings.
- scarface74 7y agoIt’s also easier to avoid buffer overflows in C by using the “n” variants of C string library functions.
- xmprt 7y agoWhy subject yourself to that risk when you can just use C++ and make everyone's lives easier? Is there a benefit to using C?
- scarface74 7y agoWhat “risk” is there in an overflow from using strncmp, strncpy, etc? C++ still isn’t as easy to interop with other languages as C and the low level APIs built into operating systems are not going to use C++/STL and you still end up converting to standard C strings and arrays.
- naniwaduni 7y agostrncpy 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.
- SamReidHughes 7y agoOh god no, because then you have to add string growth logic when you run out of space, and there's all sorts of opportunities to fuck that up.
- avip 7y agoSmart pointers make it exponentially easier to write memory-safe code in C++ than in C.