[SDL] Strings, seg faults, and memory

wwp subscript at free.fr
Sun Jun 26 01:14:36 PDT 2005


Hello Matt,


On Sat, 25 Jun 2005 23:54:12 -0700 Matt Pruett <entelin at logicaldreams.net>
wrote:

> Though not directly an sdl question I have come to need dynamic strings
> to work with sfont and things with sdl, I figgured you guys would be
> able to answer this rather simply.
> 
> I am used to declaring and reading/writing to a string in this
> fassion...
> 
> char* str;
> sprintf (str,"%i",1234);
> etc...
> 
> However I find that segfaults, as does any attempt to write to char*
> post declaration as apparently gcc makes it a   const char*  instead.
> However if I do a calloc and specify the specific size it will be fine,
> as such..
> 
> 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?

You're right, that's a C question (maybe you're interesting in posting to
linux-c-programming, see http://vger.kernel.org/majordomo-info.html).

Defining a char* doesn't allocate any room for your string manipulation
at all, it just creates a pointer to what you have to allocate, then.

Using malloc/calloc is the right way, but you might find more convenient to
use arrays of chars like this:

  char str[100];
  sprintf(str, "%i", 1234);

Take care of not buffer overflowing str[] when putting chars in it. str
allows storing 100 chars, from str[0] to str[99], including a trailing zero
(storing "foo" in it would eat 4 chars), so don't put more than 100 chars in
it. See snprintf too (man printf), which allows storing chars in str, w/ a
size limit for security.


Regards,

-- 
wwp




More information about the SDL mailing list