I’m learning the use of the switch statement and using the rand() and srand() functions but then I’m getting a segmentation fault when I try to run this code I got from this book I’m learning C from. What’s could be causing this to happen?
#include <stdio.h>
int main(void)
{
int iRandomNum = 0;
srand(time());
iRandomNum = (rand() % 4) + 1;
printf("\nFortune Cookie - Chapter 3\n");
switch (iRandomNum) {
case 1:
printf("\nYou will meet a new friend today.\n");
break;
case 2:
printf("\nYou will enjoy a long and happy life.\n");
break;
case 3:
printf("\nOpportunity knocks softly. Can you hear it?\n");
break;
case 4:
printf("\nYou'll be financially rewarded for your good deeds.\n");
break;
} //end switch
printf("\nLucky lotto numbers: ");
printf("%d ", (rand() % 49) + 1);
printf("%d ", (rand() % 49) + 1);
printf("%d ", (rand() % 49) + 1);
printf("%d ", (rand() % 49) + 1);
printf("%d ", (rand() % 49) + 1);
printf("%d\n", (rand() % 49) + 1);
} //end main function
You’re calling
time()with no arguments. Thetime()function takes one argument, and it’s not optional.Add
to the top of your source file, and change the
srand()call toEDIT :
You also need to add
to get the declarations of
srand()andrand().EDIT 2:
You can often (seemingly) get away with calling a function without
#includeing the header in which it’s declared.In C90, if you call a function with no visible declaration, the compiler implicitly creates a declaration for it, assuming that the function returns
intand takes the arguments given in the call. Bothsrand()andrand()do in fact returnintresults, so calls to them could work. Buttime()takes an argument of typetime_t*, and returns a result of typetime_t; a call with no declaration might work if you’re “lucky”, or it might blow up in your face.The 1999 ISO C standard (C99) changed the rules, so calling a function without a visible declaration is a constraint violation, requiring a diagnostic from the compiler.
Even in C90 mode, most compilers can be persuaded to warn about undeclared functions if you give them the right options.
Bottom line: If you’re going to call a library function, read its documentation (man page, whatever) and add a
#includefor the header that declares it. And don’t count on the compiler to remind you if you forget to do this.