Review the implementation of getchar in cs50c Note that CHAR

Review the implementation of get_char in cs50.c. Note that CHAR_MAX is a constant defined in limits.h that specifies the maximum value that a char can hold. Read up on sscanf, as via man or Google Review the implementation of get_string and teardown in cs50.C.Note that the destructor attribute causes teardown to be called automatically after main has completed or exit has been called in a program. Read up on static, as via Google. Answer the below in reading.txt. below in reading.txt Questions 1. (2 points.) Why do we return CHAR MAX on failure in get_char (when its call to get_string returns NULL) rather than NULL? 2. (2 points.) If get_char, per its own name, is meant to get just one char from a user, why do we try to read two via sscanf? 3. (2 points.) Why do we declare allocations and strings as static? What might happen if we didn\'t? 4. (2 points.) How does the library ensure that every string allocated by get_string is eventually freed?

Solution

1. On failure get_char raises an exception rather than NULL and produces a null pointer. So there should be exception handling to avoid the failure. But if we use char_max it return NULL when we get an error.

2. get_char() reads a single character input from the console but sscanf reads from the character string s. So from the given character string s we can read th character using sscanf function but not getchar().

3. Static allocation means allocating memory for variables when the program starts. This meory is fixed and cannot be changed during execution.

Static String: String means constant. Static string means string stored in one particular location.

When a declaration or allocation doesnt include any access specifier , the context in which the declaration takes place determines the default accessibility.

4. GetString() allocates memory for the string but it doesnt free that memory. We need to use free() function to free that memory. But if we forget this, then it may cause memory leaks.

So to avoid this problem the modern operating systems are designed such that when a program exists with memory leaks, the memory gets free by itself.

But it is a good practice to free the memory after our usage in the program.

 Review the implementation of get_char in cs50.c. Note that CHAR_MAX is a constant defined in limits.h that specifies the maximum value that a char can hold. Re

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site