NO

Author Topic: sprintf bug or not?  (Read 3997 times)

akko

  • Guest
sprintf bug or not?
« on: July 13, 2012, 11:53:53 AM »
Why does the following code produce an access violation error? (PC ver 7.00.350)

Code: [Select]
#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

  • Guest
Re: sprintf bug or not?
« Reply #1 on: July 13, 2012, 12:10:25 PM »
It's because you are trying to change a string constant.
 
Code: [Select]
#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....
 
Code: [Select]
#include <stdio.h>
#include <stdlib.h>

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

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

 
« Last Edit: July 13, 2012, 12:12:27 PM by CommonTater »

akko

  • Guest
Re: sprintf bug or not?
« Reply #2 on: July 13, 2012, 01:34:56 PM »
Thanx -- I "should" have thought about it but...   :)

This one works okay too:

Code: [Select]
#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

  • Guest
Re: sprintf bug or not?
« Reply #3 on: July 13, 2012, 02:16:02 PM »
Thanx -- I "should" have thought about it but...   :)

No worries... glad I could help.

czerny

  • Guest
Re: sprintf bug or not?
« Reply #4 on: July 13, 2012, 07:11:22 PM »
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

Code: [Select]
char *c = "xxx...xxx";

CommonTater

  • Guest
Re: sprintf bug or not?
« Reply #5 on: July 14, 2012, 02:00:52 AM »
Don't know if it is clear to you. The error is not in the sprintf call but in

Code: [Select]
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.