c - 分配给 : should I have to free it? 的指针

标签 c memory malloc free

假设我有这段代码:

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++ 对其进行了标记,因此您永远不应使用 mallocfree。使用 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/

相关文章:

c - 将加密文件中的二进制数据写入指定的内存位置

c - malloc 一个 char 和 null 终止符

c - 如果堆栈变量被 malloc 重新分配,会发生什么情况?

c - "Use of uninitialised value"尽管有 memset

c - OSX 10.6 上的 pwrite() 不支持 64 位偏移量

c - 将数据从结构体插入 C 中的堆栈

memory - Ascii 表的物理位置在哪里

c - 如何创建共享头内存exe和dll/共享对象

c - 如何实现【复制数组到链表】功能?

c - 如何使用 C union 来使多个命名变量和另一个更大的命名变量相等?