I am writing a program for a basic slot machine, randomly generating numbers and displaying the corresponding "symbols" for them from an array. The program executes most of the time but randomly I get an error code -1073741819 (0xC0000005). I'm extremely new to C so I'm unfamiliar with a lot of things, including what exactly can be causing this error in my code.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
srand(time(NULL));
char *symbols[] = {"Pineapple", "Kiwi", "Orange", "Lime", "Peach",
"Lemon", "Pear", "Banana", "Cherry", "Grape", "Blueberry",
"Blackberry", "Apricot"};
int num1, num2, num3;
int balance;
printf("Enter initial balance (in cents): ");
scanf("%d", &balance);
num1 = (rand() % (13 - 0 + 1)) + 0;
num2 = (rand() % (13 - 0 + 1)) + 0;
num3 = (rand() % (13 - 0 + 1)) + 0;
printf("%s ", symbols[num1]);
printf("%s ", symbols[num2]);
printf("%s ", symbols[num3]);
printf("\n");
if ((num1 == num2) && (num1 == num3))
{
printf("Congratulations! You have won $1");
balance += 100;
printf("\n");
}
balance -= 5;
printf("Remaining Balance: %d", balance);
return 0;
}
The error as I said happens randomly and I haven't been able to reliably reproduce it. Sometimes only 1/3 fruit names prints and I get the error code, sometimes it's 2 and sometimes none prints.
The statement (rand() % (13 - 0 + 1)) + 0;
is equivalent to rand() % 14
which will generate random numbers from 0-13 INCLUSIVE. The problem is that you only have 13 strings, so when the rng spits out a 13
, the fruit at index 13
doesn't exist.
This can be fixed by either adding another fruit or by changing your rng to rand() % 13
This:
num1 = (rand() % (13 - 0 + 1)) + 0;
Is the same as:
num1 = rand() % 14;
Which means you're generating a number from 0 to 13. Your symbols
array has 13 elements with indexes from 0 to 12. So when you randomly generate the value 13, you're reading past the end of the array. Doing so invokes [undefined behavior]9https://en.wikipedia.org/wiki/Undefined_behavior), which in this case causes your program to crash.
Change that line and the two that follow to:
num1 = (rand() % 13;
num2 = (rand() % 13;
num3 = (rand() % 13;
That way you get a number from 0 to 12.
You are randomly accessing an invalid 14th element of symbols
array (which has 13 elements).
When you write
num1 = (rand() % (13 - 0 + 1)) + 0;
you are trying to calculate symbols index. But this could lead to index 13... and symbols[13]
does not exist, and it will translate in accessing a memory location you are not supposed to access.
Write simply
num1 = rand() % 13;
and everything will be fine.
User contributions licensed under CC BY-SA 3.0