c - 总是(可移植地)释放并为进程保留内存或返回操作系统

标签 c malloc

我读到 free() “通常”不会将内存返回给操作系统。我们可以方便地利用 free() 的这个特性吗?例如,这是可移植的吗?

 /* Assume I know i would need memory equivalent to 10000 integers at max
    during the lifetime of the process */

 unsigned int* p = malloc(sizeof(unsigned int) * 10000);

 if ( p == NULL)
  return 1;

 free(p);

 /* Different points in the program */

 unsigned int* q = malloc(sizeof(unsigned int) * 5);

 /* No need to check for the return value of malloc */

我正在编写一个演示,我可以提前知道要支持多少个调用上下文

是否可以预先分配“n”“call contexts”结构,然后立即释放它们。这能保证我以后的 malloc 调用不会失败吗?

这在效率方面有什么优势吗?我在想,如果最初获取了一大块并且现在免费提供,那么少一个“if”检查加上内存管理会更好。这会减少碎片吗?

最佳答案

您最好保留分配的初始内存块,然后使用池使其可供应用程序中的客户端使用。依靠深奥的行为来维护代码的稳定性不是好的形式。如果任何发生变化,您可能会处理错误的指针并导致程序崩溃。

关于c - 总是(可移植地)释放并为进程保留内存或返回操作系统,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3087439/

相关文章:

c - 指向 char 数组的指针数组

c - 在c中使用指针将二维数组传递给函数

c - 为什么这个比较返回 false?

c - 这个指针应该这样操作吗?基础C

c - 在 C 中使用 fread() 分配内存和读取数组的最便携方法

c - 如何将 const unsigned char* payLoad 转换为 char* 并复制它?

arrays - 函数中 str[strlen(src)+1] 和 char *str=(char*)malloc((strlen(src)+1)*sizeof(char)) 的区别

c - 在 Linux 中不使用 fsync 写入和读取同一个 fd

C - 如何在没有 string.h 和动态内存分配的情况下连接字符串

c - 在 C 中,无法释放 NULL 并将其分配给 char 指针