Home > Mobile >  In C, I understand why not to return the address of a local variable in a pointer returning function
In C, I understand why not to return the address of a local variable in a pointer returning function

Time:11-09

I have the following code:

int* foo(){
int x = 15;
return &x; }

Which I understand why not to do since the local variable address gets erased from the stack after the function finishes and it becomes a dangling pointer. The question is, how do I not make it a dangling variable without making x a static variable

CodePudding user response:

Either allocate memory from the heap inside the function

int *f() {
  int *foo = malloc(sizeof(int));
  if(!foo) {
    // Do appropriate error handling here
  }
  return foo;
}

Don't forget to free it at some point though.

Or you pass in a pointer to a variable living outside the function:

void f(int *foo) {
  *foo = 42;
}

void g() {
  int goo;
  f(&goo);
}

CodePudding user response:

The blessed ways are:

  • return a value and not an address

      int foo(){
          int x = 15;
          return x;
      }
    
  • have the caller to provide an address

      int *foo(int *x) {
          *x = 15;
          return *x;
      }
    

    or

      void foo(int *x) {
          *x = 15;
      }
    
  • Return dynamic (allocated) memory:

      int *foo() {
          int *x = malloc(sizeof(*x));
          // should test valid allocation but omitted for brievety
          *x = 15;
          return x;
      }
    

    Beware, the caller will take ownership or the allocated memory and is responsable to free it later.

  • Related