I keep hitting a segmentation fault when calling anything that reads from stdin. I have no idea why. Calling getchar() or any other similar function from within a certain function causes my program to crash, but when I call it from another function, it works fine. Here’s the part that crashes:
int prompt()
{
int i;
int selection = -1;
while (selection < 0 || selection > 9) {
printf("Item:\n\n");
for (i = 0 ; i < 10 ; i++) {
printf("%d) %s\n", i, getItemName(i));
}
for (i = 0 ; i < 11 ; i++) {
printf("\n");
}
printf("Select the number of the corresponding item: ");
char input = getchar(); <--- dies here!
if (input != EOF && input != '\n') flush();
selection = atoi(input); <--- error here!
}
return selection;
}
void flush() {
char c = getchar();
while (c != EOF && c != '\n')
c = getchar();
}
UPDATE After a lot of exprimenting, I found out that the issue was with the code I marked out. (the atoi()). I was passing it a simple char, rather than a char*. I still don’t get why when I used a bunch of printfs, it would die at the line I specified, and not before the call to atoi().
If you compile and run it with a debugger, you will find that the problem is actually in your
atoicall.atoitakes achar *, so you are telling it to convert the string at address0x00000030(for'0') to a number, and that is an invalid address.in gdb:
Compiling with warnings would also have told you this: