当应在C函数返回新分配的内存? [英] When should a C function return newly allocated memory?
问题描述
在其他地方的响应,我发现下面的代码片段:
在总体上是在C更好的有
来电者分配内存,而不是
被调用 - 因此,为什么strcpy的是一个更好
功能,在我看来,比的strdup。
块引用>我可以看到这是一个有效的模式,但为什么它会被认为是更好?在那里按照这种模式的优点?还是不行?
例如
最近,我已经写了,看起来像code了相当数量的:
结构美孚* A = foo_create();
//做一个东西
foo_destroy(一);如果
富
是一个什么比一个扁平结构越多,那么我想我可以把我所有的初始化一步到位。此外,假定结构应堆。为什么它可能是更好的形式做一些事情,如:结构美孚* A =的malloc(sizeof运算(富));
foo_init(一);
//做一个东西
foo_destroy(一)
解决方案当你想要一个不透明的结构,不希望暴露其内部的头文件。你的
foo_create()
例子说明了这一点。又如是Windows API。例如。
的CreateWindow
为您提供了一个HWND
。你不知道实际的WND
结构是什么样子的,不能触摸它的领域。同样的,内核对象句柄。例如。
CreateEvent
给出了一个HANDLE
。你只能用良好定义的API操纵它,并用CloseHandle的关闭()
。回复:
结构美孚* A =的malloc(sizeof运算(富));
这需要你在头定义
结构美孚
,从而暴露其内部结构。如果你想改变它下降的轨道,你可能破坏现有的code,它(错误地)依赖于直接的成员。In a response elsewhere, I found the following snippet:
In general it is nicer in C to have the caller allocate memory, not the callee - hence why strcpy is a "nicer" function, in my opinion, than strdup.
I can see how this is a valid pattern, but why might it be considered nicer? Are there advantages to following this pattern? Or not?
example
Recently I've written a fair amount of code that looks something like:
struct foo *a = foo_create(); // do something with a foo_destroy(a);
If
foo
is a anything more than a flat structure, then I figured I could put all my initialization in one step. Also, assume the struct should be on the heap. Why might it be better form to do something like:struct foo *a = malloc(sizeof(foo)); foo_init(a); // do something with a foo_destroy(a)
解决方案Whenever you want an opaque structure and don't want to expose its internals in the header file. Your
foo_create()
example illustrates this.Another example is the Windows API. E.g.
CreateWindow
gives you aHWND
. You have no idea what the actualWND
structure looks like and can't touch its fields.Same with kernel object handles. E.g.
CreateEvent
gives aHANDLE
. You can only manipulate it with the well-defined API, and close it withCloseHandle()
.Re:
struct foo *a = malloc(sizeof(foo));
This requires you to define
struct foo
in a header, and hence expose its internals. If you want to change it down the track, you risk breaking existing code that (incorrectly) relied on its members directly.这篇关于当应在C函数返回新分配的内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!