-1

I want my function "ordenafile" to take candidatos.000 - candidatos.068. For some reason si[0] is bugged i think, cause if I make the program prints si[0], it crashes. Anyone knows why?

 int i;
char si[1],si2[2],sname[20]="candidatos.00",sname2[20]="candidatos.0";
for(i=0;i<=68;i++){ 
    if (i<=9){
        itoa(i,si,10);
        sname[12]=si[0];
        ordenafile(sname);
    }
    itoa(i,si2,10);
    sname2[12]=si2[0];
    sname[13]=si2[1];
    ordenafile(sname);

}
skaffman
  • 398,947
  • 96
  • 818
  • 769
Syan Souza
  • 149
  • 12
  • 1
    Try to use `sprintf(str, "%d", value)` instead of `itoa`, as `itoa` is not a standard function. – SSC Nov 28 '14 at 01:11
  • 2
    For starters, `si[1]` too short for a C string, since `si[1]` is supposed to be `0`. http://stackoverflow.com/questions/190229/where-is-the-itoa-function-in-linux – Déjà vu Nov 28 '14 at 01:13

1 Answers1

1

Your program causes a buffer overflow, itoa writes two characters to a buffer of size 1. To fix this, make it char si[2]; . You forgot about the null terminator.

You also need to increase the size of si2.

To avoid this sort of error, use snprintf instead of itoa (which is a non-standard function anyway), e.g.:

snprintf(si2, sizeof si2, "%d", i);

Then you will never get a buffer overflow. If you get the buffer size wrong then you get the wrong number , which is not quite so bad.

M.M
  • 138,810
  • 21
  • 208
  • 365