I have the following code:
int get_int(void) {
char input[10];
fgets(input, 10, stdin); // Segfault here
return atoi(input);
}
It gives me a segfault where marked. I have absolutely no idea what the issue is, because I have the following code in a different program:
int main(void) {
char card[17];
printf("Number: ");
fgets(card, 17, stdin);
printf("%s\n", card_type(card));
return 0;
}
And it works fine. I am 100% sure it isn't segfaulting on the atoi.
Is this reproducible by others, I'm on Linux amd64 using GCC 4.4.5. It compiled and output no warnings.
Since it was requested, here is the code that calls get_int:
void get_input(int *inputs) { // Stop cluttering up my main
printf("M spotting F: ");
inputs[0] = get_int();
printf("F spotting M: ");
inputs[1] = get_int();
printf("F spotting F: ");
inputs[2] = get_int();
printf("M spotting M: ");
inputs[3] = get_int();
}
The code that calls that is:
int main(void) {
int *inputs[4];
int *heights[4];
get_input(*inputs);
get_heights(*inputs, *heights);
print_bars(*heights);
printf("M4F F4M F4F M4M\n");
}
And thus you have reached the top of the call stack.
Segmentation faults are a common class of error in programs written in languages like C that provide low-level memory access and few to no safety checks. They arise primarily due to errors in use of pointers for virtual memory addressing, particularly illegal access.
Core Dump/Segmentation fault is a specific kind of error caused by accessing memory that “does not belong to you.” When a piece of code tries to do read and write operation in a read only location in memory or freed block of memory, it is known as core dump. It is an error indicating memory corruption.
Use debuggers to diagnose segfaults Start your debugger with the command gdb core , and then use the backtrace command to see where the program was when it crashed. This simple trick will allow you to focus on that part of the code.
On a Unix operating system such as Linux, a "segmentation violation" (also known as "signal 11", "SIGSEGV", "segmentation fault" or, abbreviated, "sig11" or "segfault") is a signal sent by the kernel to a process when the system has detected that the process was attempting to access a memory address that does not ...
Your declarations for the input (and probably height) arrays should be int inputs[4];
You want an array of integers, not an array of pointers to integers. You then want to call the functions with just inputs
and heights
as the parameters.
What you are doing now is creating an array of 4 pointers to integers. And then calling the function with *inputs
will pass only the first pointer in that array to the function get_int
. The get_int
function will attempt to use the first pointer to integer as an array, which is not the behavior you want.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With