I made a program that involves a lot of randomization.
It all works fine, except for array number 5 char a5
, which includes 2 strings. There's a 5% chance of any of them appearing.
Once I execute my program, random symbols appear once in a while, if I launch it enough times, I hear the "Critical stop" error sound but no visible error.
My program has an input loop to prevent me from launching it again, which I'll keep here for ease of use.
Here's the minimal code:
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <windows.h>
main(){
srand (time(NULL));
int j, v;
char i, mlt [6], a5[2][6] = {" x2", " x3"};
do{
system ("cls");
for (j=0; j<10; j ){
v = rand () % 95;
char* b4[6] = {a5[v]};
char mik[10] = (" ");
strcpy (mlt, mik);
strcat (mlt, *b4);
printf (" %s\n", mlt);
}
printf ("Press 'n' to exit... ");
scanf (" %s", &i);
}
while (i!='n' && i!='N');
}
Here's a screensnip example of a random launch (on my normal program):
CodePudding user response:
There are at least two major issues:
scanf (" %s", &i);
will lead to buffer overflow for any input besides enter.int v = rand () % 95
will yield a number between 0 and 94, yet you usev
to index intoa5
which is out of bounds forv > 1
.
Other minor issues:
i
is usually a integer loop variable, not wrong, but I changed it toc
.- Reduce scope of variables and consider eliminating the ones you don't really need.
- The correct declaration for main is
int main(void)
(orint main(int, char **)
.
Here is how I modified your program:
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
int main() {
srand(time(NULL));
for(;;) {
for (int j=0; j<10; j ) {
printf(" x%d\n", (rand() % 2) 2);
}
printf ("Press 'n' to exit... ");
char c;
if(!scanf("%c", &c) || toupper(c) == 'N')
break;
}
return 0;
}