Why is below two codes provide different results?

84 views Asked by At
  1. The first piece of code is:

    #include <stdio.h>
    char *getString()
    {
        char *str = "Will I be printed?";
        return str;
    }
    int main()
    {
        printf("%s", getString());
    }
    
  2. And the second piece of code is:

    #include <stdio.h>
    char *getString()
    {
        char str[] = "Will I be printed?";
        return str;
    }
    int main()
    {
        printf("%s", getString());
    }
    

In both of the above codes,char pointer is returned which points to a local variable which could get overwritten but still code-1 manages to run successfully while code-2 print Garbage values.

1

There are 1 answers

4
bukkojot On

Let a little extend your example and see where stored our data:

#include <stdio.h>

char* some_static_var="123";

char *getString1()
{
    char *str = "Will I be printed?";
    return str;
}

char *getString2()
{
    char str[] = "Will I be printed?";
    return str;
}

int main()
{
    int some_var_at_stack=1;
    printf("%p\n", &some_var_at_stack);
    printf("%p\n", some_static_var);
    printf("%p\n", getString1());
    printf("%p\n", getString2());
}

What we got? At my 32-bit system:

0xbfc2005c

0x80497bc

0x8048554

0xbfc20035

As you can see, char* var="123" points in data segment (https://en.wikipedia.org/wiki/Data_segment), but char[] located at stack.

Every time, when you leave your function where you alloc any variables at stack, this variables get undefined, since data allocated at stack (pointers too) invalid outside function. But in getString1() actually returns pointer value to data segment which outside stack, so this function works correctly, but allocated pointer get undefined at function exit.