Created
September 25, 2013 15:35
-
-
Save JustonDavies/6701452 to your computer and use it in GitHub Desktop.
C string realloc and concat
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
char * strautocat(char **buffer, const char *str1) //char **buffer, const char *format, vargs? Ive done this before | |
{ | |
assert(str1 != NULL); assert(buffer != NULL); | |
if(*buffer == NULL){*buffer = (char *)calloc(sizeof(char)*DEFAULT_STRING_LENGTH,sizeof(char));} | |
size_t allocated_size, required_size; | |
allocated_size = malloc_usable_size(*buffer); | |
required_size = strlen(str1)+strlen(*buffer)+1; | |
while(required_size > allocated_size) | |
{ | |
printf("Growing buffer from %d to accomidate %d\n", allocated_size, required_size); | |
*buffer = (char *)realloc(*buffer, malloc_usable_size(*buffer)*2); | |
allocated_size = malloc_usable_size(*buffer); | |
} | |
strcat(*buffer, str1); | |
return *buffer; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Should malloc_usable_size() be really used in production code?
Notes from the man pages:
The value returned by malloc_usable_size() may be greater than the requested size of the allocation because of alignment and minimum size constraints. Although the excess bytes can be overwritten by the application without ill effects, this is not good programming practice: the number of excess bytes in an allocation depends on the underlying implementation.
The main use of this function is for debugging and introspection.