Is this C appender safe, and reasonably optimal?
#define REALLOC_BUFFER_SIZE 4096
char *append(char *orig_str, size_t *orig_str_size, const char *append_str) {
// no action required if appending an empty string
if (append_str[0] == 0) {
return orig_str;
}
// does the current char* have enough space?
size_t req_space = strlen(orig_str) + strlen(append_str) + 1; // +1 for NULL byte
// resize if the required space is greater than the original buffer size.
if (req_space > *orig_str_size) {
// prepare the variable with the amount of space we want
size_t allocate = *orig_str_size + req_space + REALLOC_BUFFER_SIZE;
char *new_str = (char *)realloc(orig_str, allocate);
// resize success..
if (new_str == NULL) {
fprintf(stderr, "Couldn't reallocate memory\n");
return NULL;
}
// the realloc didn't fail, here is our new pointer
orig_str = new_str;
// overwrite the free space with NULL's
memset(orig_str + strlen(orig_str), 0, req_space);
// copy the appending text to the string
strcpy(orig_str + strlen(orig_str), append_str);
// modify the original size
*orig_str_size = allocate;
} else {
// append the string
strcpy(orig_str + strlen(orig_str), append_str);
}
return orig_str;
}
Example usage:
char *buffer;
size_t buffer_size = 20;
int i;
buffer = (char *)malloc(sizeof(char) * buffer_size);
strcpy(buffer, "1234567890123456789"); // fill some data prior..
// original string
for (i=1; i < 100; ++i) {
buffer = append(buffer, &buffer_size, "AABBCC");
}
free(x);
Latest changes: GitHub