简体   繁体   English

在 C 中,我理解为什么不在指针返回函数中返回局部变量的地址,但我该如何解决?

[英]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问题是,如何在不使 xa 静态变量的情况下使其成为悬空变量

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.不要忘记在某个时候free它。

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.请注意,调用者将获得所有权或分配的内存,并负责稍后释放它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我无法返回指向局部变量的指针,但我可以返回指向 c 中的局部结构数据的指针? - I cannot return pointer to local variable, but I can return pointer to data of local struct in c? 将本地指针变量的地址返回给main()函数 - Returning an address of a local pointer variable to main() function 为什么不能将指向固定大小数组的指针的地址传递给期望指向C中指针的函数? - Why can't I pass the address of a pointer to a fixed size array into a function expecting a pointer to a pointer in C? C - 函数返回指向局部变量的指针 - C - function returning a pointer to a local variable 函数返回C中局部变量错误的地址 - Function returning address of local variable error in C 如何解决C中的指针错误? - How can I fix a pointer error in C? 返回变量地址的 function 如何返回零? - How can a function returning the address of the variable return zero? 在C语言中,我可以通过堆栈指针访问另一个函数中main函数的局部变量吗? - In C language, can I access local variable of main function in another function through stack pointer? C语言可以修改指针变量的地址吗? - Can I change the address of the pointer variable in C language? 为什么我可以通过指针转换而不是C中的全局变量来更改本地const变量? - Why can I change a local const variable through pointer casts but not a global one in C?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM