Skip to content

Instantly share code, notes, and snippets.

@markusfisch
Last active August 29, 2015 14:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save markusfisch/11398095 to your computer and use it in GitHub Desktop.
Save markusfisch/11398095 to your computer and use it in GitHub Desktop.
Format data and automatically allocate memory to be of sufficient length

maprintf

Format data and automatically allocate memory to be of sufficient length.

This is a care-free alternative to snprintf() with strings of arbitrary length.

Sample

char *buf = maprintf( "%s: %s", key, value );

/* do something with buf */

free( buf );
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include "maprintf.h"
/**
* Format data and automatically allocate memory to be of sufficient length
*
* @param format - printf format description
* @param ... - arguments
*/
char *maprintf( const char *format, ... )
{
va_list ap;
char *buf;
int len;
int req;
va_start( ap, format );
len = vsnprintf( NULL, 0, format, ap );
va_end( ap );
if( len < 1 ||
!(buf = (char *)calloc( ++len, sizeof( char ) )) )
return NULL;
va_start( ap, format );
req = vsnprintf( buf, len, format, ap );
va_end( ap );
if( req < 0 ||
req >= len )
{
free( buf );
return NULL;
}
return buf;
}
#ifndef _maprintf_h_
#define _maprintf_h_
char *maprintf( const char *, ... );
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment