Video Coming Soon...
WARNING: This exercise needs a full review to match recent changes to C. If you find problems please report them with the bug feature (top right, bug icon).
35: Safer Strings
Talk about what happened when Rust proved me right. Also, get rid of bstrlib and see if something else will work. Maybe write our own? Maybe antirez stuff? vstr? What's the latest library that polishes the C string turd.
Why C Strings Were a Horrible Idea
When people talk about problems with C, they say its concept of a string is one of the top flaws. You've been using these extensively, and I've talked about the kinds of flaws they have, but there isn't not much that explains exactly why C strings are flawed and always will be. I'll try to explain that right now, and after decades of using C's strings, there's enough evidence for me to say that they are just a bad idea.
It's impossible to confirm that any given C string is valid:
- A C string is invalid if it doesn't end in
'\0'. - Any loop that processes an invalid C string will loop infinitely (or, just create a buffer overflow).
- C strings don't have a known length, so the only way to check if they're terminated correctly is to loop through them.
- Therefore, it isn't possible to validate a C string without possibly looping infinitely.
This is simple logic. You can't write a loop that checks if a C string is valid because invalid C strings cause loops to never terminate. That's it, and the only solution is to include the size. Once you know the size you can avoid the infinite loop problem. If you look at the two functions I showed you from Exercise 27, you see this:
Register for From Impostor to Programmer
Register today for the course and get the all currently available videos and lessons, plus all future modules for no extra charge.