Please bear with me, I am a learner…

I wrote a program in C having dangling pointer:

#include<stdio.h>

int *func(void)
{
    int num;
    num = 100;
    return &num;
}

int func1(void)
{
    int x,y,z;
    scanf("%d %d",&y,&z);
    x=y+z;
    return x;
}

int main(void)
{
    int *a = func();
    int b;
    b = func1();
    printf("%d\n",*a);
    return 0;
}

I am getting the output as 100 even though the pointer is dangling.

I made a one-time change in the above function func1(). Instead of taking the value of y and z from standard input as in the above program, now I am assigning the value during compile time.

I redefined the func1() as follows:

int func1(void)
{
    int x,y,z;
    y=100;
    z=100;
    x=y+z;
    return x;
}

Now the output is 200. I am confused!

Can somebody please explain to me the reason for the above two outputs?

4 Spice ups

It’s because of the way the memory gets allocated.

After calling func and returning a dangling pointer, the part of the stack where num was stored still has the value 100 (which is what you are seeing afterward). We can reach that conclusion based on the observed behavior.

After the change, it looks like what happens is that the func1 call overwrites the memory location that “a” points to, with the result of the addition inside func1 (the stack space previously used for func is reused now by func1), so that’s why you see 200.

Of course, all of this is undefined behavior so while this might be a good philosophical question, answering it doesn’t really buy you anything. Read this resource for clearing all the concepts about the topic.

2 Spice ups