itoa function not working

1.7k views Asked by At

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);

}
1

There are 1 answers

0
M.M On BEST ANSWER

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.