Search code examples
cscopeundefined-behaviorc-stringsstorage-duration

why char array is empty in C


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.


Solution

  • Wonderful!

    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:

    1. dynamic memory allocation (which means you need to free it)
    2. passing in a buffer (adds parameters ... you should pass in the length)
    3. using a static buffer (problematic for threading or multiple uses)
    4. returning a structure by value containing the text (can copy more than it should, which could cause performance issues, and you have to save the structure in the caller)
    5. eliminating this function altogether (which might not be a good solution depending on what you are doing)