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

Josh Matthews mrlachatte at gmail.com
Sun Jun 26 15:37:45 PDT 2005


Doesn't that give you huge memory leaks if you use that frequently?

Josh

On 6/27/05, Michael L. <sdl at tossed.org> wrote:
> 
> 
> >
> > 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) );
> 
> _______________________________________________
> SDL mailing list
> SDL at libsdl.org
> http://www.libsdl.org/mailman/listinfo/sdl
>




More information about the SDL mailing list