[SDL] Strings, seg faults, and memory
mystml at adinet.com.uy
Sun Jun 26 11:08:44 PDT 2005
> I am used to declaring and reading/writing to a string in this fassion...
> char* str;
> sprintf (str,"%i",1234);
> However I find that segfaults, as does any attempt to write to char*
> post declaration as apparently gcc makes it a const char* instead.
No, it's because you declare a pointer to char, but it doesn't really
point to a bunch of chars that actually belong to you.
> 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?
Yes, you do have to make sure your pointers point to something, but
there's no need to make them dynamic. The following also works :
sprintf(str, "%i", 1234);
More information about the SDL