Reputation: 1181
I'm having problem with my program. The variables are written in italian, I'm sorry! I have to handle the penalties phase of a football game. If in the first five penalties the teams end tie, they will go for penalties to the end.
if (retiPrimaSquadra != retiSecondaSquadra){
buffer = fopen("buffer.txt", "w");
fprintf(buffer, "%d-%d", retiPrimaSquadra, retiSecondaSquadra);
fclose(buffer);
return 0;
} else {
printf("Risultato secondo tempo supplementare: %d - %d\n\n", retiPrimaSquadra, retiSecondaSquadra);
printf("RIGORI\n");
int rigoreA=0, rigoreB=0;
char vRigoreA[5];
char vRigoreB[5];
int rigore=0;
int i=0;
vRigoreA[i]='x';
//printf("%c", vRigoreA[i]);
for(i=0; i<5; i++){
//tiro prima squadra
rigore = (rand() % 101);
if(rigore <= 75){
rigoreA++;
retiPrimaSquadra++;
vRigoreA[i]='x';
}
else{
vRigoreA[i]='o';
}
//tiro seconda squadra
rigore = (rand() % 101);
if(rigore <= 75){
rigoreB++;
retiSecondaSquadra++;
vRigoreB[i]='x';
}
else{
vRigoreB[i]='o';
}
//stampa xo
printf("%c %c\n", vRigoreA[i], vRigoreB[i]);
}
//risultato 5 rigori
printf("%d - %d\n", rigoreA, rigoreB);
char enter = '\0';
while(enter != '\n'){
enter = getchar();
}
//OLTRANZA
while(rigoreA==rigoreB){
//tiro prima squadra
rigore = (rand() % 101);
if(rigore <= 75){
rigoreA++;
retiPrimaSquadra++;
vRigoreA[i]='x';
} else {
vRigoreA[i]='o';
}
//tiro seconda squadra
rigore = (rand() % 101);
if(rigore <= 75){
rigoreB++;
retiSecondaSquadra++;
vRigoreB[i]='x';
}
else{
vRigoreB[i]='o';
}
//stampa xo
printf("%c %c\n", vRigoreA[i], vRigoreB[i]);
}
printf("check\n");
}
buffer = fopen("buffer.txt", "w");
fprintf(buffer, "%d-%d", retiPrimaSquadra, retiSecondaSquadra);
fclose(buffer);
}
The program runs with no errors if it doesn't enter in the last "while". Otherwise, after finishing the while cycle, when it goes to right the results in the buffer.txt file, it gives me a stack smashing detected problem. I really don't know how to handle it, cause it seems so stupid that if it doesn't enter the while it goes fine!
Upvotes: 0
Views: 495
Reputation: 5477
You are using i
to access your vRigoreA
array in the while (vRigoreA[i]='x';
). However, i
is set to 5
after your for
-loop, so you are accessing stack memory not belonging to the array. At the end of the function, the debugger detects that out-of-bounds writes happened.
Upvotes: 2