Skip to content

Instantly share code, notes, and snippets.

@JustonDavies
Created September 25, 2013 15:35
Show Gist options
  • Save JustonDavies/6701452 to your computer and use it in GitHub Desktop.
Save JustonDavies/6701452 to your computer and use it in GitHub Desktop.
C string realloc and concat
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;
}
@dmundt
Copy link

dmundt commented May 3, 2022

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment