5. Here\'s a short program, echo.c, that prompts the user to enter a string from
ID: 3627212 • Letter: 5
Question
5. Here's a short program, echo.c, that prompts the user to enter a stringfrom the standard input and then echos the string back to the standard
output:
#include <stdio.h>
#include <stdlib.h>
char buffer[1024 + 1];
char* prompt_and_read() {
printf(" Please enter a string (-1 to exit): ");
fgets(buffer, 1024, stdin);
return buffer;
}
int main() {
while (1) {
char* ptr = prompt_and_read();
int flag = atoi(ptr); /* converts string to int */
if (flag < 0) break; /* break out of the loop */
printf("You entered: %s ", ptr);
}
return 0;
}
Note that array named buffer is not a local variable in
prompt_and_read but rather is defined outside of all functions.
(In C jargon, buffer is an extern variable.) Why is buffer
extern rather than auto?
Explanation / Answer
In the 2nd version, buffer[1024 + 1] is allocated on the stack and
thus is in the call frame of prompt_and_read. When prompt_and_read
returns, the storage for buffer thus can be reallocated to some
other use (e.g., the caller might call another function whose
call frame then overwrites buffer). The guiding rule is this:
In a function, never return a pointer to a stack address.
In the first version, buffer is basically part of the program's
load module. In particular, storage for buffer is not allocated on
the stack and thus exists independently of calls to prompt_and_read.
Note on Java/C#, etc. In these languages, arrays are like objects
in that they are newed:
// Java prompt_and_read
char[ ] prompt_and_read() {
char[ ] buffer = new char[1024 + 1];
...
return buffer; // OK, buffer points to storage on the heap, not the stack
}
The Java buffer will be garbage-collected from the heap.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.