Pelles C forum

C language => Beginner questions => Topic started by: akko on July 13, 2012, 11:53:53 AM

Title: sprintf bug or not?
Post by: akko on July 13, 2012, 11:53:53 AM
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;
}
Title: Re: sprintf bug or not?
Post by: CommonTater on July 13, 2012, 12:10:25 PM
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;
}


Title: Re: sprintf bug or not?
Post by: akko on July 13, 2012, 01:34:56 PM
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;
}

Title: Re: sprintf bug or not?
Post by: CommonTater on July 13, 2012, 02:16:02 PM
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.
Title: Re: sprintf bug or not?
Post by: czerny on July 13, 2012, 07:11:22 PM
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";

Title: Re: sprintf bug or not?
Post by: CommonTater on July 14, 2012, 02:00:52 AM
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.