我有一个关于动态内存分配的问题。
背景信息:我正在编写一个程序,读取一个单词的文本文件并计算每个单词出现的频率(每行一个单词)。
这个特定的函数会读取文件,计算行数和字符数,然后动态分配内存给字符串指针数组、存储每行字符数的数组以及字符串本身。(其他部分与我的问题没有直接相关性。)
问题:如果我空间不足时,应该多久重新分配内存一次?我为初始内存分配值设置了一个常量(“memstart”)。在下面的代码片段中,每当行数超过“memstart”时就进行重新分配。如果每次增加内存空间时,我重新分配一个更大的内存块,程序会更快吗?
像这样的事情最好的做法是什么?
代码片段:
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()
将其修剪到最终大小。 - ad absurdum