C程序设计:malloc和free一个循环内 [英] C Programming: malloc and free within a loop
问题描述
我刚开始用C和对性能问题知之甚少与的malloc()
和免费()
。我的问题是这样的:如果我打电话给的malloc()
然后按免费()
A <$ C $内C>,而循环,循环,比如说,20次迭代,将相对于调用它运行速度较慢免费()
的 循环?
我实际上使用第一种方法来分配存储器给一个缓冲器,从文件中读出的可变长度字符串,执行一些串操作,然后每次迭代后清除缓冲器。如果大量的开销我的方法结果的话,我想要求一个更好的办法,我要达到同样的效果。
对不起,我英文不好。
更新0:非常感谢所有帮助,貌似我还有很多东西要学! ; d
感谢和问候,
氏/ P>
肯定慢。 (但是,请记住,你需要平衡的malloc
和免费
,否则你得到一个内存泄漏。数量)
如果长度因人而异,你可以使用的realloc
来扩大缓冲区的大小。
无效* V =的malloc(1024);
为size_t BUFSIZE = 1024;而(条件){
为size_t reqbufsize = get_length();
如果(reqbufsize&GT; BUFSIZE){
BUFSIZE = reqbufsize * 2;
V = realloc的(V,BUFSIZE);
}
//你也可以缩小它。 do_something_with_buffer(五);
}免费(V);
I just started out with C and have very little knowledge about performance issues with malloc()
and free()
. My question is this: if I were to call malloc()
followed by free()
inside a while
loop that loops for, say, 20 iterations, would it run slower compared to calling free()
outside the loop?
I am actually using the first method to allocate memory to a buffer, read a variable-length string from a file, perform some string operations, and then clear the buffer after every iteration. If my method results in a lot of overhead then I'd like to ask for a better way for me to achieve the same results.
Sorry for my bad English.
update 0: thanks so much for all the help, looks like I still have much to learn! ;D
Thanks and regards, K
Definitely slower. (But remember you need to balance the number of malloc
and free
otherwise you get a memory leak.)
If the length varies, you can use realloc
to expand the buffer size.
void* v = malloc(1024);
size_t bufsize = 1024;
while(cond) {
size_t reqbufsize = get_length();
if (reqbufsize > bufsize) {
bufsize = reqbufsize * 2;
v = realloc(v, bufsize);
}
// you may shrink it also.
do_something_with_buffer(v);
}
free(v);
这篇关于C程序设计:malloc和free一个循环内的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!