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:
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?
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:
int *init1(int *a) {
*a = 10;
return a;
}
int main() {
int a;
init1(&a);
int *b = init1(&(int) {0});
}
int init2() {
return 10;
}
int main() {
int a = init2();
}
#include <stdlib.h>
int *init3() {
int *p = malloc(sizeof *p);
if(p)
*p = 10;
return p;
}
int main() {
int *a = init3();
free(a);
}