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);
}
Your program causes a buffer overflow,
itoa
writes two characters to a buffer of size1
. To fix this, make itchar 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 ofitoa
(which is a non-standard function anyway), e.g.: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.