Sprintf access violation

I have a problem with the following code:

for(i = 0;(i - 1)< n;i++)
{
char* b;
sprintf(b, "%d", i);
}

      

It compiles fine, but when I run it, it gives me the infamous "Access violation to 0XC0000005" error. I've tried setting b to NULL, "," 0 ", 0 and a bunch of other things, but then I get the error" Access violation to 0XC0000005 "or" Expression: string! = NULL. Any help would be appreciated!

+1


source to share


5 answers


sprintf

writes data to an existing buffer, which you pass into it as the first parameter. Currently you are not specifying a value for b at all, which means (IIRC in C) the value can be anything. If you set it to NULL or 0, it sprintf

will try to write to memory starting at address 0.

You need to create a buffer of the appropriate size so that sprintf can write to it. For example:



for(i = 0;(i - 1)< n;i++)
{
    char b[10];
    sprintf(b, "%d", i);
}

      

Regardless of how you want to allocate the buffer depends on what your real code wants to do with the results, of course.

+7


source


Umm ... Your pointer to b contains garbage because you haven't initialized it or allocated space. Springtf requires you to allocate the destination buffer space ...



At a minimum, you want something like char b [50] or whatever maximum size you expect, not just char *.

+1


source


A char * is an uninitialized pointer to a char or char array. You need to define a buffer char [10], otherwise sprintf's target address will be undefined.

+1


source


sprintf requires you to pass it an already allocated character buffer large enough to hold any possible result. This is highly dependent on buffer overflows - you will most likely want to use the secure snprintf instead. One inefficient but safe way to do this:

int bufsize = snprintf(NULL, 0, formatstring, ...);
char *buffer = malloc(bufsize+1); # count doesn't include trailing nul
if (buffer == NULL) out_of_memory_error();
snprintf(buffer, bufsize+1, formatstring, ...);

      

+1


source


Many thanks! Since I need char *, I rewrote the code:

for(i = 0;(i - 1)< n;i++)
{
char* b;
char a[100];
b = a;
sprintf(b, "%d", i);
}

      

and it works like a charm. Finally I can get on with my life! Thank you very much again!

0


source







All Articles