简体   繁体   中英

In C, I understand why not to return the address of a local variable in a pointer returning function, how can I fix it though?

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 xa static variable

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);
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM