为什么在函数malloc内存和可用它外面是一个坏主意? [英] Why malloc memory in a function and free it outside is a bad idea?
问题描述
如果这是一个坏主意,如何在功能分配内存?
if this is a bad idea, how to allocate memory in the function?
推荐答案
这不是一个坏主意,而是有时一个坏主意,它可以对编程很多想法可说的。
It's not a "bad idea", but rather "sometimes a bad idea", which can be said about many ideas in programming.
分配在函数内部存储器和外部释放它可以是普通的设计图案,通过的方式。试想一下:
Allocating memory inside a function and releasing it outside may be a common design pattern, by the way. Consider:
// hashtable is a typedef-ed pointer type
hashtable ht = hashtable_new();
// .. do something with hashtable
hashtable_free(ht);
HT
函数中的 hashtable_new
被分配内外也发布了,但你会一遍又一遍地看这个模式在地段好的C code的。
ht
was allocated in a function hashtable_new
and released outside it, yet you will see this pattern over and over in lots of good C code.
它做什么节目,但是,是如何在同一的逻辑单元的(哈希表ADT)负责分配和取消分配。这使得很多的意义 - 因为谁知道如何分配的人,最知道如何释放。分配和不同的逻辑单元释放的是更多的时候是一个坏主意。
What it does show, however, is how the same logical unit (the hash-table ADT) takes care of allocation and de-allocation. This makes lots of sense - because the one who knows how to allocate, knows best how to deallocate. Allocating and releasing in different logical units is more often a bad idea.
这篇关于为什么在函数malloc内存和可用它外面是一个坏主意?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!