开发者

C - fgets segfault

开发者 https://www.devze.com 2023-02-14 06:47 出处:网络
I have the following code: int get_int(void) { char input[10]; fgets(input, 10, stdin); // Segfault here

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: ");
    开发者_如何学Goinputs[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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号