Wednesday, November 17, 2021

[SOLVED] Segmentation fault when returning pointers

Issue

I recently started learning C, and an issue came up with this code:

#include <stdio.h>
#include <stdlib.h>

int* add(int* a,int* b)
{
        //a and b are pointers to integers
        int c=(*a)+(*b);
        return &c;
}

int main()
{
        int x=2,y=4;
        int* z=add(&x,&y); //call by reference
        printf("sum=%d\n", *z);
        return 0;
} 

This supposedly works in windows machines, but when I compiled it, this issue came up:

gcc -o hello return.c
return.c: In function ‘add’:
return.c:8:9: warning: function returns address of local variable [-Wreturn-local-addr]
    8 |  return &c;
      |  ^~
./hello
Segmentation fault (core dumped)

This post describes what happened here, but it didn't happen on the windows machine in the tutorial I've been following, and my friends' windows machine can run it too.Is there a way i can emulate this behaviour on the gcc compiler?

Additionally, could someone explain why the error doesn't happen in windows? The stack frame, after being destroyed,shouldn't allow that address to be accessed again from what I understand, so why wouldn't this carry over for DOS based systems?


Solution

int* add(int* a,int* b)
{
        //a and b are pointers to integers
        int c=(*a)+(*b);
        return &c;
}

It is an awful approach since after returning the function, the local variable c's location is not guaranteed that it points to a valid address.

So, you should either use malloc/calloc functions or make c static variable.



Answered By - snr