从stdin读取fgets分段错误

时间:2018-02-19 00:27:52

标签: dynamic-memory-allocation fgets c-strings

我目前正在尝试使用fgets()从标准输入读取一行,但我得到了一个分段错误(我不再解决分段错误,请参阅编辑)

int main(void)
{
    char selection;
    string firstName = NULL;

    printf("[A]dd a new client \n");
    printf("[D]isplay all clients \n");
    printf("[I]ncome Average for all clients \n");
    printf("[Q]uit \n");  

    selection = fgetc(stdin);
    printf("\n");

    switch (selection) {
    case 'A':
        printf("First name: ");
        fgets(firstName, MAXNAMESIZE, stdin);
        printf("\n");

        ...
    }
}

这是编译器的输出:

[A]dd a new client 
[D]isplay all clients 
[I]ncome Average for all clients 
[Q]uit 
A

First name: Segmentation fault

谢谢!

编辑:

我已经改变了这样的代码:

int main(void)
{
    char selection;
    string firstName;

    printf("[A]dd a new client \n");
    printf("[D]isplay all clients \n");
    printf("[I]ncome Average for all clients \n");
    printf("[Q]uit \n");  

    selection = fgetc(stdin);
    printf("\n");

    switch (selection) {
        case 'A':
            if ((firstName = malloc(MAXNAMESIZE * sizeof(char))) == NULL)
                return 1;
            printf("First name: ");
            fgets(firstName, MAXNAMESIZE, stdin);
            printf("\n");

        ...
    }
}

但是现在我无法输入任何名字,程序就此结束了。这是输出:

~/workspace/ $ ./test
[A]dd a new client 
[D]isplay all clients 
[I]ncome Average for all clients 
[Q]uit 
A

First name: 
~/workspace/ $ 

1 个答案:

答案 0 :(得分:0)

您必须先malloc firstName才能使用它,因此请务必#include <stdlib.h>

尝试string firstName = malloc(MAXNAMESIZE * sizeof(char));

始终检查malloc的结果是否为NULL

此外,在程序结束时或者您认为free(firstName)更有用时可以防止内存泄漏。