0

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?

  • 1
    Returning a dangling pointer (a pointer to a local variable) is not a compilation error. It just invokes Undefined Behaviour. That means that from that point anything can happen, from the expected result to a program crash passing by unexpected results. In real world it depends on implementation details that nobody wants to care for. The rule is just **DON'T**. – Serge Ballesta Nov 09 '21 at 09:35
  • 1
    "Additionally, could someone explain why the error doesn't happen in windows?" See the linked duplicate and also [What is undefined behavior and how does it work?](https://software.codidact.com/posts/277486) – Lundin Nov 09 '21 at 09:40

1 Answers1

0
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.

  • 1
    Makeing `c` static will resolve the issue, but this approach is awful too. The best approach here is just not return an address to the result but just return the result: `int add(int *a, int *b) {return *a + *b;}` or even better `int add(int a, int b) {return a + b;}` – Jabberwocky Nov 09 '21 at 09:51