Reading Someone Else’s Code
Recall that functions like get_char
and get_string
from the CS50 Library are declared in a file called cs50.h
that you can #include
in your own programs. Those functions are actually implemented in a file called cs50.c
, which you can see at https://gist.github.com/dmalan/522bc25f1f4c362525beca2be4ec016e.
-
Review the implementation of
get_char
incs50.c
. Note thatCHAR_MAX
is a constant defined inlimits.h
that specifies the maximum value that achar
can hold. -
Read up on
sscanf
, as viaman
or Google. -
Review the implementation of
get_string
andteardown
incs50.c
. Note that thedestructor
attribute causesteardown
to be called automatically aftermain
has completed orexit
has been called in a program. -
Read up on
static
, as via Google.
Answer the below in reading.txt
.
Questions
-
(2 points.) Why do we return
CHAR_MAX
on failure inget_char
(when its call toget_string
returnsNULL
) rather thanNULL
? -
(2 points.) If
get_char
, per its own name, is meant to get just onechar
from a user, why do we try to read two viasscanf
? -
(2 points.) Why do we declare
allocations
andstrings
asstatic
? What might happen if we didn’t? -
(2 points.) How does the library ensure that every
string
allocated byget_string
is eventually freed?
Debrief
-
Which resources, if any, did you find helpful in answering this problem’s questions?
-
About how long did you spend on this problem’s questions?