问题
I wrote the following:
#include <stdio.h>
#include <string.h>
char* getString();
char* getString(){
char str[10];
gets(str);
return str;
}
int main() {
char* s;
s=getString();
strcpy(s,"Hi");
puts(s);
return 0;
}
I know that the length of str
must be less than 10, but even when I wrote just "Hi", nothing was being printed. as far as I see it, it should be Ok. the compiler says that fgets is dangerous and should not be used
.
What is the reason that nothing being printed on the screen?
回答1:
char str[10];
// ...
return str;
This is wrong!!! Local variables are invalidated when their scope exits; thus using returned array is undefined behavior. You have to malloc a string and return it:
return strdup(str);
回答2:
Problem pertaining to result have already being discussed. List of solutions that you can do includes:
1). define str globally as "char str[10]" and use it in function main and getString
2). Use malloc/calloc in function getString, code goes something like this...
char* getString(){
char *str = NULL;
str = (char *)calloc(10, sizeof(char));
gets(str);
return str;
}
int main() {
char* s;
s=getString();
strcpy(s,"Hi");
puts(s);
free(s);
return 0;
}`
3). use static for ready help. But it is not conceptually correct approach
e.g. declare as follows in function getString
static char str[10];
回答3:
The simplest way of getting your code working, though not necessarily the best way, is to make str
static.
i.e.
static char str[10];
回答4:
Well str[10]
is a an array of 10 characters allocated on the stack. The stack is removed after the function is out of scope. Hence the address that was returned by the function getString()
is no longer valid.
Consider declaring a pointer char *str
and dynamically allocating memory with malloc
. Now your variable points to a location in the heap which continues to remain even after the function has finished executing.
Hope it answered your question
来源:https://stackoverflow.com/questions/11517298/strings-and-string-functions-in-c