简体   繁体   English

释放函数本地的指针并返回该指针

[英]Free a pointer local to a function and return the pointer

I have a C code similar to this. 我有一个与此类似的C代码。 How can I free the pointer and return it ? 我如何释放指针并返回它? If I create another local pointer variable and assign p to that local pointer variable, it is showing a warning that local variable pointer cannot be returned. 如果创建另一个本地指针变量并将p分配给该本地指针变量,则显示警告,表明无法返回本地变量指针。 Note that I have a recursion so I want to free up the pointer in the function itself. 请注意,我有一个递归,所以我想释放函数本身中的指针。 Any workaround. 任何解决方法。 Thanks in advance. 提前致谢。

char * ABCfunction(){
    char * p = malloc(10*sizeof(char));
    //do something with p
    ABCfunction();
    return p;
    //free(p); //Want to do both.
}  

UPDATE: Yes, I know that it makes no sense and we cannot do both. 更新:是的,我知道这没有任何意义,我们不能同时做到。 I am asking for an alternative approach. 我要求一种替代方法。 The problem is if I don't free the pointer, it is consuming a lot of memory for high input values. 问题是,如果我不释放指针,那么高输入值会消耗大量内存。 I want to get rid of high memory usage. 我想摆脱高内存使用率。

Want to do both. 想要两者都做。

That is not a good goal. 那不是一个好目标。

If you free the pointer, you should not return the pointer. 如果释放指针,则不应返回指针。 Otherwise, the calling function will get a dangling pointer. 否则,调用函数将获得一个悬空指针。

Note that I have a recursion so I want to free up the pointer in the function itself. 请注意,我有一个递归,所以我想释放函数本身中的指针。

Make sure you capture the returned pointer, use it, and then free it. 确保捕获返回的指针,使用它,然后释放它。

Here's what your function should look like: 这是您的函数应如下所示:

char * ABCfunction()
{
   char * p = malloc(10*sizeof(char));
   //do something with p

   char* p1 = ABCfunction();
   // Use p1.
   // Then free p1
   free(p1);

   return p;
}  

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

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