sprintf bug or not?

Started by akko, July 13, 2012, 11:53:53 AM

Previous topic - Next topic

akko

Why does the following code produce an access violation error? (PC ver 7.00.350)


#include <stdio.h>
#include <stdlib.h>

int main(void)
{   char *c = "xxx...xxx";

   sprintf(c+3, "%d", 123);
   printf(c); // should print: xxx123
   return 0;
}

CommonTater

#1
It's because you are trying to change a string constant.


#include <stdio.h>
#include <stdlib.h>

int main(void)
{   char c[12] = "xxx...xxx";

   sprintf(&c[3], "%d", 123);
   printf(c); // should print: xxx123
   return 0;
}


Or, most correctly....


#include <stdio.h>
#include <stdlib.h>

int main(void)
{   char c[8];

   sprintf(c, "xxx%d", 123);
   printf(c); // should print: xxx123
   return 0;
}



akko

Thanx -- I "should" have thought about it but...   :)

This one works okay too:


#include <stdio.h>
#include <stdlib.h>

int main(void)
{ char c[] = "xxx...xxx";  // <--- c[]  instead of  *c

sprintf(c+3, "%d", 123);
printf(c); // should print: xxx123
return 0;
}


CommonTater

Quote from: akko on July 13, 2012, 01:34:56 PM
Thanx -- I "should" have thought about it but...   :)

No worries... glad I could help.

czerny

Quote from: akko on July 13, 2012, 11:53:53 AM
Why does the following code produce an access violation error? (PC ver 7.00.350)

Don't know if it is clear to you. The error is not in the sprintf call but in


char *c = "xxx...xxx";


CommonTater

Quote from: czerny on July 13, 2012, 07:11:22 PM
Don't know if it is clear to you. The error is not in the sprintf call but in


char *c = "xxx...xxx";


Hi Czerny:
There's nothing wrong with using a pointer to a string constant, it's done all the time.

The access violation comes from attempting to change a constant value; the string in this case.