[英]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.