Search code examples
cfunctionstack

Diffrent results after printing the same variable in C


So a friend of mine showed me a weird thing with printf() in C.

#include <stdio.h>
#include <string.h>
int *init()
{

    int a =10;
    int *p = &a;
    return p;
}
int main()
{

    int *a = init();
    printf("FIRST printf and value of a: %u\n", *a);
    printf("SECOND printf and value of a %u\n", *a);
    return 0;
}

Now I expected to get the same result at both printf() calls but that's not the case as seen in this snip:output Of course, you can try it on your own system to convince yourselves. I think it has something to do with the printf() function frame but I don't understand fully enough what is happening. Can you explain it to me please?


Solution

  • Returning the address of a local variable is undefined behavior as its lifetime expired when the function returned. On my platform the local variable is stored on the stack, and the memory where the variable a or p was stored was overwritten by subsequent function calls (printf()).

    Consider these alternatives instead:

    1. Pass in pointer to the caller's variable.
    int *init1(int *a) {
        *a = 10;
        return a;
    }
    
    int main() {
       int a;
       init1(&a);
    
       int *b = init1(&(int) {0}); 
    }
    
    1. Return value instead of a pointer.
    int init2() {
       return 10;
    }
    
    int main() {
       int a = init2();
    }
    
    1. Dynamically allocate space for your variable, and caller takes on the obligation to free the variable when done. Usually you name such a function "create" or "new" rather than "init".
    #include <stdlib.h>
    
    int *init3() {
        int *p = malloc(sizeof *p);
        if(p) 
            *p = 10;
        return p;
    }
    
    int main() {
       int *a = init3();
       free(a);
    }