0
votes

I'm currently trying to read a line from stdin using fgets() but i'm getting a segmentation fault (i'm not geting the segmentation fault anymore, please see edit)

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");

        ...
    }
}

This is the compiler's output:

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

First name: Segmentation fault

Thank you!!

Edit:

i've changed the code like this:

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");

        ...
    }
}

But now i'm not able to enter any name, the program just ends. This is the output:

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

First name: 
~/workspace/ $ 
1
Whats string?tkausl
string is definfed as char* (typedef char* string)Santiago Aguilar
And where does it point to?wildplasser
to NULL. i tried using string firstName; and string firstName = " "; but in the first case firstName is uninitialized and in the second i also get a segmentation faultSantiago Aguilar

1 Answers

0
votes

You need to malloc firstName before you can use it, hence make sure to #include <stdlib.h>.

Try string firstName = malloc(MAXNAMESIZE * sizeof(char));

Always check that the result of malloc is not NULL.

Moreover, at the end of your program or when you think it's more useful free(firstName) to prevent memory leaks.