应该使用 realloc 吗?
在查看了一些开源项目的 C 代码之后,我不确定我是否做对了。
当我创建字符串 (char *) 时,我通常会这样做:
#define DEF_LEN 10
char *mystring;
mystring = malloc(DEF_LEN*sizeof(char));
当我更改字符串时(通常在函数内完成):
mystring = realloc(mystring, strlen(newstring)*sizeof(char)+1);
strcpy(mystring,newstring);
在许多开源项目中,我看到许多开发人员只是这样做:
char another_string[1024];
问题:
- 是我对
realloc
的使用还好吗? - realloc 是性能杀手吗(如我的代码中/经常使用的那样)?
After looking at some open source projects C code I'm not sure if I'm doing stuff right.
When I'm creating strings (char *), I've normally done this:
#define DEF_LEN 10
char *mystring;
mystring = malloc(DEF_LEN*sizeof(char));
When I'm changing my string (normally done within a function):
mystring = realloc(mystring, strlen(newstring)*sizeof(char)+1);
strcpy(mystring,newstring);
On lots of open source projects I see that many dev's just do:
char another_string[1024];
Questions:
- Is my usage of
realloc
okay? - Is
realloc
a performance killer (as used in my code / very often)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
哇哦...
在 C 语言中是一个严重的禁止。如果
realloc
失败,那么您就失去了free
mystring
的能力,因为您已经用NULL
覆盖了它。在性能和可靠性方面,我一直喜欢堆栈上的固定长度缓冲区。这确实取决于您的要求。如果您的数据集有上限,那么使用固定长度缓冲区就很好。你只需要非常小心,不要超出缓冲区之类的。话又说回来,在 C 语言中,您始终必须关注
NUL
终止缓冲区并确保不会溢出它们。Whoa there ...
is a serious no-no in C. If
realloc
fails, then you have lost your ability tofree
mystring
since you have overwritten it withNULL
.In terms of performance and reliability, I have always liked fixed length buffers on the stack. It really does depend on your requirements. If you have caps on your data sets, then using fixed length buffers is great. You just have to be very careful not to overrun buffers and what not. Then again, in C you always have to be concerned with
NUL
terminating buffers and making sure that you don't overrun them.