假设我有这段代码:
for (int i=0;i<n;i++) {
//compute z
float *p = (float *) malloc (sizeof(float)*z);
//do something with p
}
请注意,p
未在其他任何地方使用,并且每个 for
循环都相互独立。
假设 z
不是很大,所以 single p
在内存方面并不那么昂贵。但是,n
可能很大,因此 p
占用的总内存可以保持一致。
free()
是否正确:
for (int i=0;i<n;i++) {
//compute z
float *p = (float *) malloc (sizeof(float)*z);
//do something with p
free(p);
}
奖励问题:如果时间性能是优先考虑的(而不是内存消耗),最好避免 free(p)
,因为它很耗时?
最佳答案
由于您使用 C++ 对其进行了标记,因此您永远不应使用 malloc
和 free
。使用 smart pointers (或者 new
/delete
如果您无法访问兼容 C++11 的编译器)。
for (int i=0;i<n;i++) {
// compute z
std::unique_ptr<float[]> p{new float[z]};
// do something with p
// p gets automatically freed at the end of the scope
}
回答您的问题:
Is it correct to free() it with...
是的。如果您使用 malloc
分配一些东西,您总是需要释放
它。
would be better to avoid the free(p), since it's time consuming?
是的。考虑在循环外预先分配内存位置。
// preallocate
std::unique_ptr<float[]> p{new float[z]};
for (int i=0;i<n;i++) {
// clear p
// compute z
// do something with p
}
// p gets automatically freed at the end of the scope
关于c - 分配给 : should I have to free it? 的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40992251/