[SDL] Re: Strings, seg faults, and memory

Michael L. sdl at tossed.org
Sun Jun 26 13:12:24 PDT 2005



> 
> char* str = (char*)calloc(10,sizeof(char));
> 
> so the question is, to I have to alloc all my strings? or is there a
> better/simpler way of dealing with it?

I use a function called Va(), which allows you to do this on the spot, 
thereby creating less verbose code.  This is tested on Win32, Linux and 
OS X.

The memory for the strings is static, and part of the Va() function 
itself.  The result of too many recursions is undefined.

#define MAX_RECURSIONS 4
#define MAX_LONG_STRING 4096

char *Va( char *format, ... )
{
     static char string[MAX_RECURSIONS][MAX_LONG_STRING];
     static int  callNum = 0;


     /* Begin arg printing */
#ifdef WIN32

     va_list ap;
     va_start( ap, format );
	int len = _vscprintf( format, ap ) + 1;
	if ( len > MAX_LONG_STRING )
	{
		printf("Overflow: Message too large.\n");
		return NULL;
	}
     vsprintf( string[callNum], format, ap );
     va_end( ap );

#else

     va_list ap;
     va_start( ap, format );
     if ( vsnprintf( string[callNum], MAX_LONG_STRING, format, ap ) > 
MAX_LONG_STRING )
     {
         printf("Overflow: Message too large.\n");
         return NULL;
     }
     va_end( ap );

#endif
     /* End arg printing */


     int oldCall = callNum;
     callNum++;
     if ( callNum >= MAX_RECURSIONS )
         callNum = 0;

     return string[oldCall];
}

/* Sample usage */
void SetName( char *nameStr );

SetName( Va("%s the %ser", name, titleVerb) );




More information about the SDL mailing list