我读到 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/