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!
source to share
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.
source to share
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, ...);
source to share