views:

533

answers:

5

Hi, 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 give me the infamous "0XC0000005 Access Violation" error. I have tried setting b to NULL, "", "0", 0 and a bunch of other stuff but then I get the "0XC0000005 Access Violation" error or "Expression: string != NULL. Any help would be appreciated!

+1  A: 

Umm... Your pointer to b contains garbage since you haven't initialized it or allocated space. Springtf requires you to have allocated a destination buffer space...

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

Uri
Thanks, I am still learning c++.
+6  A: 

sprintf writes data into an existing buffer, which you pass into it as the first parameter. Currently you're not specifying a value for b at all, which means (IIRC in C) the value could be anything. If you set it to NULL or 0, sprintf is going to try to write into memory starting at address 0.

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

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

Whether that's actually how you want to allocate the buffer depends on what your real code wants to do with the results, of course.

Jon Skeet
Thanks this all finally makes sense!
+1  A: 

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

devio
Okay, that makes sense!
A: 

Thank you very much! Since I needed a char* I rewrote the code to:

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

and it works like a charm. I can finally now get on with my life! Once again thank you very very much!

You could have just used a in place of b there. What are you doing with it afterward? If your char* points to an auto array like that, it won't be reliable after the block in which the array is declared.
ysth
+1  A: 

sprintf requires to pass it an already allocated character buffer large enough to store any possible result. This is highly subject to buffer overflows - you probably want to use the safer snprintf instead. One inefficient but safe way to do that:

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, ...);
ysth
Good point! Thanks!