gpt4 book ai didi

C 编程 - 应该多久使用一次 realloc?

转载 作者:太空狗 更新时间:2023-10-29 17:01:22 24 4
gpt4 key购买 nike

我有一个关于动态内存分配的问题。

上下文:我正在编写一个程序,该程序读取单词的文本文件并计算每个单词出现的频率(每行一个单词)。

这个特定的函数读取文件,计算行数和字符数,然后动态地将内存分配给字符串指针数组,该数组存储每行的字符数和字符串本身。 (其他部分与我的问题不太直接相关)。

问题:如果空间不足,我应该多久重新分配一次内存?我设置了一个常量(“memstart”)来设置初始内存分配值。在下面的代码片段中,我为每一行都重新分配了“memstart”的值。如果重新分配更大的内存块而不是每次将内存空间增加 1 个“变量类型”,程序会处理得更快吗?

对于这样的事情,什么是最佳实践?

代码片段:

int read_alloc(FILE* fin, FILE *tmp, char **wdp, int *sz){
int line_cnt= 0, chr, let=1;
do{
chr=getc(fin);
let++;
//count characters

if(chr!=EOF){
chr=tolower(chr);
fputc(chr, tmp);
}
//convert to lcase and write to temp file

if ('\n' == chr || chr==EOF){
sz[(line_cnt)]=((let)*sizeof(char)); //save size needed to store string in array
*(wdp+(line_cnt))=malloc((let)*sizeof(char)); //allocate space for the string
if ((line_cnt-1) >= memstart){
realloc(wdp, (sizeof(wdp)*(memstart+line_cnt))); //if more space needed increase size
realloc(sz, (sizeof(sz)*(memstart+line_cnt)));
}
line_cnt++;
let=1;
}
} while (EOF != chr);

return (line_cnt);
}

最佳答案

虽然问题是关于 realloc 的频率应该被调用,看看 OP 的代码,我认为最好从应该如何安全开始。

C11 标准规定(n1570 草案,§ 7.22.3.5realloc 函数,强调我的):

Synopsis

#include <stdlib.h>
void *realloc(void *ptr, size_t size);

Description
The realloc function deallocates the old object pointed to by ptr and returns a pointer to a new object that has the size specified by size. The contents of the new object shall be the same as that of the old object prior to deallocation, up to the lesser of the new and old sizes. Any bytes in the new object beyond the size of the old object have indeterminate values.
If ptr is a null pointer, the realloc function behaves like the malloc function for the specified size. (...). If memory for the new object cannot be allocated, the old object is not deallocated and its value is unchanged.
Returns
The realloc function returns a pointer to the new object (which may have the same value as a pointer to the old object), or a null pointer if the new object could not be allocated.

现在让我们考虑问题中的这个片段,其中 sz声明为 int* sz;

realloc(sz, (sizeof(sz)*(memstart+line_cnt)));

返回值丢失了,所以我们不知道调用是否成功,如果成功了,sz无效。此外,sizeof(sz)是指针的大小,而不是指针类型 ( int )。

一个更安全(和正确)的模式是:

size_t new_size = /* Whatever, let's say */ size + SOME_COSTANT + size / 2;
void *tmp = realloc(ptr, new_size * sizeof *ptr);
if ( tmp == NULL ) {
/* Deal with the error, e.g. log a message with perror, return NULL
(if this is in a function) or just give up, but remeber that
realloc doesn't invalidate nor free 'ptr' on failure */
exit(EXIT_FAILURE);
}
ptr = tmp; // <- on success, realloc invalidated ptr
size = new_size;

现在,回答问题,realloc应仅在需要时调用,因为它涉及可能 扩展系统调用。因此,要么提前分配一大块,要么选择一个不断增长的策略,比如每次都将大小加倍(或 1.5 倍)。

值得注意的是,如果可能的话,操作系统可以在不复制原始数组的任何元素的情况下执行重新分配。

关于C 编程 - 应该多久使用一次 realloc?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47625515/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com