News:

Download Pelles C here: http://www.smorgasbordet.com/pellesc/

Main Menu

sprintf

Started by cane, October 19, 2005, 08:01:18 PM

Previous topic - Next topic

cane

WTF is this?! Every kind of shit is coming out! :evil:


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

typedef struct {
  char a1[7];
} foo;

foo x;

char y[7];

int main(int argc, char *argv[])
{
   sprintf(x.a1,"%.6X",rand());
   sprintf(y,"%.6X",rand());

   printf("%s\n", x.a1);
   printf("%s\n", y);

   return 0;
}


The big problem is with the char arry in the struct.
sprintf works "better" with char array y except for an extra char being appended (?!).

JohnF

typedef struct {
  char a1[7];
} foo;

foo x;

char y[7];

===========
sprintf Precision
The precision specifies the minimum number of characters for type d, i, o, u, x or X
===========

What happens if 8 chars are sent to the arrays?

John

cane

nothing comes out...

JohnF

Increase the char arrays to 10

======================
typedef struct {
  char a1[10];
} foo;

foo x;

char y[10];
======================

and see what happens.

John

cane

Ok, I've got it. As you said, "The precision specifies the minimum number of characters for type d, i, o, u, x or X"... I was a tricked by the fact x.a1 and y were lying one next to the other in memory and being the width of the arrays not enough to hold the strings, sprintf continued beyond the bouds. So strange stuff was printed until a null terminator was found.

Ok, let's update the bugs chart: -1 PellesC, +1 my brain...  #-o

BTW, isn't there a way to directly truncate/zero-pad the hex number with precision specifiers? That is, to specify how many digits to print AT MOST.

Thanks for the help, bye.

jack


sprintf(y,"%06X",rand());

JohnF

Quote from: "cane"Ok, I've got it. As you said, "The precision specifies the minimum number of characters for type d, i, o, u, x or X"... I was a tricked by the fact x.a1 and y were lying one next to the other in memory and being the width of the arrays not enough to hold the strings, sprintf continued beyond the bouds. So strange stuff was printed until a null terminator was found.

A typical buffer overrun, a common outcome would be a crash.

Quote
BTW, isn't there a way to directly truncate/zero-pad the hex number with precision specifiers? That is, to specify how many digits to print AT MOST.

Not that I know of because the number would become basically meaningless. However there are other things you can do.

sprintf(x.a1, "%.06X", rand() & 0xffffff);

or after the sprintf

x.a1[6] = '\0';

or

snprintf(x.a1, 7, "%.06X", rand());
x.a1[6] = '\0';

John