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

Pompei2 pompei2 at gmail.com
Mon Jun 27 02:51:02 PDT 2005


> 
> > 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.


I use another one that (I think) is more simple and (the most important) has 
no limit in the string lenght ! 
The only thing is that it will slow your game if you use it a lot of times 
in a frame.
There is no bad code in my mail, it's just in html cauz i copied the code 
and now it's in color ^^

 */* This function is taken from a gcc manual page example and adapted
to my needs.
 * FTSExp is like nothing.
 * Pompei2 at gmail.com
 */*
FTSExp char *MyAllocSPrintf( const char *fmt, ... )
{
	va_list	ap;
	char *	p	= NULL;
	int	size	= 2,
		n	= 0;

	*/* AllocStr simply allocs a char * (with malloc) and fills it with '\0' s */*
	*if*( NULL == (p = AllocStr( size )) )
		*return* NULL;
	*while*( 1 ) {
		*/* Try to print in the allocated space. */*
		va_start( ap, fmt );
		n = vsnprintf( p, size, fmt, ap );
		va_end( ap );#ifndef _WIN32
		*/* If that worked, return the string. */*
		*if* (n > -1 && n < size)
			*return* p;
		*/* Else try again with more space. */*
		*if* (n > -1)
			size = n+1;
		*else* */* n <= -1 */*
			size *= 2;
#else */* NOT WIN32 */*
		*/* If that worked, return the string. */*
		*if* (n > -1 && n < size - 1)
			*return* p;
		*/* Else try again with more space. */*
		*if* (n > -1)
			size += 1;
		*else* */* n <= -1 */*
			size *= 2;
#endif */* NOT_WIN32 */*
		*/* MyRealloc is just like the normal realloc. */*
		*if*( NULL == (p = (char *)MyRealloc( p, size )) )
			*return* NULL;
	}
}

*/* How to use it ?? it's very simple: */
* 

char *psz = NULL;
psz = MyAllocSPrintf( "Yeah, it %s !\nblablabla %d", "works perfectly", 12345 );

*/* Do your stuff ... */
* 

if( psz ) {
	free( psz );
	psz = NULL;
}

-- 
----
P.O.M.P.E.I. du 47-20
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.libsdl.org/pipermail/sdl-libsdl.org/attachments/20050627/9c14c08e/attachment-0008.htm>


More information about the SDL mailing list