Question:
Why am I getting a segfault, sprintf?
2009-11-21 21:31:32 UTC
In my small program, I am sigfaulting, why?

int main(int argc, char *argv[])
{
char *string;
int n = 5;

sprintf(string, "this is %d", n + 1);
printf(string);

return 0;
}
Three answers:
?
2009-11-21 21:38:52 UTC
*string is a pointer. As it is not assigned to point to a location with sufficient space for your sprintf expression there could be and is a segmenation fault.

char str[32];

char *string = str;

int n = 5;

sprintf(string, "this is %d", n + 1);

printf(string)



would suffice.
2009-11-21 21:41:19 UTC
Short answer, you don't currently own the variable:



char *string;



It's address in memory is currently unknown and potentially volatile. So, sprintf is doing exactly what it's supposed to do, and writing to that address. You would need to allocate space for it using malloc, and then free it when you're finished.



Also, your call to printf should look more like this:



printf("%s",string);



I hope this helps.
MyKidsFan
2009-11-21 21:38:29 UTC
You need to allocate a size to string. Instead of

char *string;



use



char string[50];



(or replace 50 with the maximum size of a string you expect)


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...