英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论