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
reallocokay? - Is
realloca performance killer (as used in my code / very often)?
Whoa there …
is a serious no-no in C. If
reallocfails, then you have lost your ability tofreemystringsince 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
NULterminating buffers and making sure that you don’t overrun them.