>> SPEAKER 1: Let's write a program that gets a string from the user without
using the CS50 Library's function GetString.
To do this, we'll go ahead and use scanf, the function that the GetString
function actually uses underneath the hood.
But I'm going to do this deliberately in a buggy way.
I'm going to do in a way that I think would be right, but it turns out that
my assumption's going to be quite, quite flawed.
And in fact, quite dangerous.
Because bugs like the one I'm about to make can be exploited by adversaries
such that your machine or your program can be taken over potentially.
>> Let's begin as follows.
First let's declare our string, otherwise known now as a char star,
and call it s.
Lets next prompt the user for a string, as with "string please." And
let's now get the string from the user using scanf, quote unquote, "%s." In
other words, let's inform scanf that we do in fact expect to get a string
from the user.
>> But now we need to tell scanf one other thing--
where to put the string that the user provides.
Well, I'm going to quite simply start with comma s, specifying that I'd like
scanf to put the string there.
I'm next going to print out something like printf "thanks for the %s
backslash n comma." And as always, I'm going to pass in the string, s.
Now let's save, compile, and run this program, and see if we can't induce
the problem I predicted.
>> Make scanf-1.
./scanf-1.
String please.
Let's provide something like, "hello." "Thanks for the null." Hmm, that's not
what I was expecting.
So what's going on here?
>> Well, it turns out because we declared s as a char star but we didn't
actually stored in s the address of an actual chunk of memory, scanf didn't
have anywhere to put the string that the user typed in.
Indeed, if the user were to now type in a much longer string than "hello,"
for instance several lines of text or several paragraphs of text, it's quite
possible that we might induce a so-called segmentation fault.
>> Because scanf isn't going to know that I haven't actually put an address
inside of s.
Rather, it's going to see some value in s, some pattern of bits that may
very well be a garbage value, there just by chance.
And scanf is still going to try to write the user string to that address,
even if it is a garbage value, which could indeed induce a crash.
>> So how are we going to fix this?