Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory Allocation: Why does this C program work? [duplicate]

Tags:

c

memory

Possible Duplicate:
Returning the address of local or temporary variable

The add function is implemented wrongly. It should return a value instead of a pointer. Why aren't any errors when ans and *ans_ptr are printed and the program even gives correct result? I guess the variable of z is already out of scope and there should be segmentation fault.

#include <stdio.h>

int * add(int x, int y) {
    int z = x + y;
    int *ans_ptr = &z;
    return ans_ptr;
}

int main() {
    int ans = *(add(1, 2));
    int *ans_ptr = add(1, 2);

    printf("%d\n", *ans_ptr);
    printf("%d\n", ans);

    return 0;
}
like image 246
Byron Avatar asked Feb 12 '26 09:02

Byron


1 Answers

The reason it 'works' is because you got lucky. Returning a pointer to a local variable is undefined behaviour (UB)!! You should not do it.

int * add(int x, int y) {
    int z = x + y; // z is a local variable in this stack frame
    int *ans_ptr = &z; // ans_ptr points to z
    return ans_ptr;
}

// At return of function, z is destroyed, so what does ans_ptr point to? No one knows.  UB results
like image 60
Tony The Lion Avatar answered Feb 14 '26 21:02

Tony The Lion



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!