For a project, I have to ask the user for a file name, and I’m reading it in character by character using getchar.
From the main, I call the function char *coursename= introPrint(); //start off to print the usage directions and get the first bit of input. That function is defined as
char *introPrint(){
int size= 20;
int c;
int length=0;
char buffer[size];
//instructions printout, cut for brevity
//get coursename from user and return it
while ( (c=getchar()) != EOF && (c != '\n') ){
buffer[length++]= c;
if (length==size-1)
break;
}
buffer[length]=0;
return buffer;
}
This is basically identical code I wrote to ask the user for input, replace the character echo with asterisks, then print out the results. Here, though, I’m getting a function returns address of local variable warning for the return statement. So why am I getting no warnings from the other program, but trigger one for this code?
You’re returning the address of
buffer, which is destroyed when it goes out of scope (when the function returns). When you try to use the returned pointer, the behavior of the program is undefined: the program may reuse the memory where the instance ofbufferwas previously located for other purposes.Use a
staticbuffer, allocate one withmallocor let the caller pass in a buffer. In the last case, the function and its caller also need to communicate about the length of the buffer somehow (by an extra argumentsize, for example).