Sample Video Frame
Exercise 36: Safer Strings
I already introduced you to the "Better String" Library in Exercise 26 when we made
devpkg. This exercise is designed to get you using bstring from now on, explain why C's strings are an incredibly bad idea, and then have you change the
liblcthw code to use bstring.
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
- 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 Learn C the Hard Way
Register today for the course and get the all currently available videos and lessons, plus all future modules for no extra charge.