Should it use 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)?
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.
精彩评论