比方说,我有这个struct
在ANSI C:ANSI C在创建结构时是否必须使用malloc()?
typedef struct _point
{
float x;
float y;
} Point;
而这个函数来创建这个struct
:
Point createpoint(float x, float y)
{
Point p;
p.x = x;
p.y = y;
return p;
}
这让我创建这个功能即struct
:
int main()
{
Point pointOne = createpoint(5, 6);
Point pointTwo = createpoint(10, 4);
float distance = calculatedistancefunc(pointOne, pointTwo);
/* ...other stuff */
return 0;
}
有人告诉我这段代码无效,因为struct
没有n在返回之前在createpoint(float x, float y)
函数中获得malloc
'd,并且struct
将被删除。 但是,当我使用我的struct
这样,它似乎并没有被删除。
所以我的问题是: 我必须要malloc
这个struct
,为什么?/为什么不?
这是恕我直言的那种病态建议。如果你想做内存管理的权利,你不应该返回一个指向你的函数分配的dinamically分配结构的指针。您应该在第三个参数中请求预先分配的指针,并将其填充到您的方法中。 – mg30rg
@ mg30rg当你可以在函数中完成并返回它时,为什么要传递一个预先分配的结构指针? – Houssni
@YassineHoussni - 由于您比编写代码更可能会读取您的代码,所以在编写舒适性时代码可读性更重要。如果将内存分配和释放保留在同一个块中,则内存泄漏将变得更加困难,因为资源仅保留在需要的确切时间段,并且每次的清理(即:'malloc()'/'getmem() '/'new')与解除分配('free()'/'freemem()'/'delete')配对。你可以很容易地发现没有delete的'new',但是你会发现'createpoint()'没有'delete'吗?维护程序员会这样做吗? – mg30rg