开发者

Should it use realloc?

开发者 https://www.devze.com 2023-04-11 12:16 出处:网络
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:

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:


Whoa there ...

mystring = realloc(mystring, strlen(newstring) * sizeof(char) + 1);

is a serious no-no in C. If realloc fails, then you have lost your ability to free mystring since you have overwritten it with NULL.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号