my code as following:
char* int2str(int val);
void main(){
char *s = int2str(1001);
printf("----s=%s\n",s);
}
char* int2str(int val){
char turnStr[10];
sprintf(turnStr, "%d", val);
//printf("turnStr=%s\n",turnStr);
return turnStr;
}
The above code print out empty string, but when I uncommented the line:printf("turnStr=%s\n",turnStr)
It was able to print out the right string.
I knew the stack space can not return when the function was over, but I'm confused about when I added printf("turnStr=%s\n",turnStr)
, it could print out the string.
The basic problem is that you returned the address of something on the stack, and it was changed by something else. I tried a recent gcc and it didn't even return the stack pointer, so I tried gcc 4.4.5 and reproduced your behavior.
I tried changing main to:
void main(){
char *s = int2str(1001);
printf("----s=%s\n",s);
s = int2str(1002);
printf("----s=%s\n",s);
}
and the second printf() output 1002.
I think what is happening is that printf has some local variables that were placed in the same location as your array and that aren't used if you have previously invoked printf().
Note that it didn't print as empty but as garbage. That garbage might start with a NUL, or not.
In any case, everyone else is right that you shouldn't do this. There are a number of solutions, including: