Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sprintf Segmentation Fault

numCheck is number between 1-1000. This code gives me a segfault only when I collect the results of sprintf in charcheck. If I simply use sprintf without using the results, I don't get a seg fault. What's happening here?

char * numString;
int charcheck = sprintf(numString, "%d", numCheck);
like image 512
syl Avatar asked Aug 25 '11 01:08

syl


3 Answers

You need to provide your own memory for sprintf. Also, don't use sprintf, but rather snprintf:

char buf[1000] = {0};

snprintf(buf, 999, ....);

Alternatively you can allocate memory dynamically:

char * buf = new char[BUFSIZE];
snprintf(buf, BUFSIZE-1, ...);
/* ... */
delete[] buf;
like image 67
Kerrek SB Avatar answered Nov 04 '22 18:11

Kerrek SB


The pointer given as the first parameter to sprintf is expected to point to a memory location where sprintf should write the formatted string.

In this case you didn't initialize numString to point to some memory you allocated for the formatted string. Since numString isn't initialized it might point anywhere, and in your case trying to write the formatted output to that location results in a segmentation fault.

like image 45
sth Avatar answered Nov 04 '22 19:11

sth


The first argument to sprintf must point to a valid buffer. You have a char* but it points to garbage.

Change your code to:

char numString[80] = { };
int charcheck = sprintf(numString, "%d", numCheck);

So that numString actually points to a valid buffer (of 80 characters in this example, all elements of which are initialised to 0).

It would also be good to use snprintf so you can pass the size of your buffer to it, which will help prevent buffer overflows:

const int bufsize = 80;
char numString[bufsize] = { };
int charcheck = snprintf(numString, bufsize - 1, "%d", numCheck);

Notice that you subtract one from the buffer size that you pass to snprintf because you don't want it to use the very last slot, which you want to make sure is NULL to denote the end of the string.

like image 2
Seth Carnegie Avatar answered Nov 04 '22 18:11

Seth Carnegie