如何同时返回并释放内存

huangapple go评论74阅读模式
英文:

How can i return and also free memory at the same time

问题

我有一个函数,它分配内存,然后填充数据,然后返回它。

我想释放这个分配的内存,但如果我在返回之前释放它,它将返回空值,而且如果我尝试在返回之后释放,因为函数在看到返回时就结束了,它不会被释放。

我尝试过像这样的方式:return (free(x));return ((x)free); 但它们没有起作用。

英文:

i have a function that allocates memory, then fills it with data and then returns it.

i want to free this allocated memory but if i free it before return it will return null, also if i try to free after return, since the function ends when it sees return, it won't free.

i tried things like return (free(x)); and return ((x)free); but they didn't work.

答案1

得分: 3

访问已释放的内存是未定义行为。因此,将指向已释放内存的指针返回是没有意义的。您只需让调用者在使用完后自行释放它。

英文:

It's undefined behaviour to access memory that has been freed. As such, it would be useless to return a pointer to memory you freed. You'll just to leave it to the caller to free it after it's done with it.

答案2

得分: 1

你可以将一个指针传递给函数,分配内存并将所需的数据写入其中。在函数返回后,数据的指针将在您的调用函数中可用,就像之前一样,内存已分配并且数据已存储。在您完成对数据的操作后,可以在那里释放内存。

英文:

You could pass a pointer to the function, allocate the memory and write the needed data into it. After the function returns, the pointer to the data will be available in your caller function same as before with the memory allocated and the data stored. You can free the memory there after you did what you wanted with the data.

huangapple
  • 本文由 发表于 2023年7月20日 10:50:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/76726382.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定