Interview Questions

Why doesn't this fragment work?

C Interview Questions and Answers


(Continued from previous question...)

Why doesn't this fragment work?

Q: Why doesn't this fragment work?
char *answer;
printf("Type something:\n");
gets(answer);
printf("You typed \"%s\"\n", answer);

A: The pointer variable answer, which is handed to gets() as the location into which the response should be stored, has not been set to point to any valid storage. It is an uninitialized variable, just as is the variable i in
int i;
printf("i = %d\n", i);

That is, in the first piece of code, we cannot say where the pointer answer points, just as we cannot say what value i will have in the second. (Since local variables are not initialized, and typically contain garbage, it is not even guaranteed that answer starts out as a null pointer.
he simplest way to correct the question-asking program is to use a local array, instead of a pointer, and let the compiler worry about allocation:
#include <stdio.h>
#include <string.h>

char answer[100], *p;
printf("Type something:\n");
fgets(answer, sizeof answer, stdin);
if((p = strchr(answer, '\n')) != NULL)
*p = '\0';
printf("You typed \"%s\"\n", answer);

This example also uses fgets() instead of gets(), so that the end of the array cannot be overwritten. Unfortunately for this example, fgets() does not automatically delete the trailing \n, as gets() would.) It would also be possible to use malloc() to allocate the answer buffer, and to parameterize the buffer size (with something like #define ANSWERSIZE 100 ).

(Continued on next question...)

Other Interview Questions