almrog
almrog

Reputation: 143

segmentation fault (core dumped) in do while loop

The following code creates a linked list, with an integer as data structure. I call the function scanf to store the numbers in a do while loop. Then it says how many nodes the list has, and at the end prints all the elements found in the list. However, for the second part I need to delete some elements of the list (this part is not finished yet), but I need to prompt the user if he wants to do so. The problem: I am trying to test if I enter anything different to Y or N, then it keeps asking the user if he wants to delete elements of the list. I receive a "SIGSEGV" error, and I do not know why. Does anyone could help me with this? It seems a problem with the declaration of the variable char * answer

#include <stdio.h>
#include <stdlib.h>


typedef struct Node {
    int number;
    struct Node * next;
} NODE;

NODE * createNode( int number )
{
    NODE * newNode;

    newNode = malloc( sizeof(NODE) );
    newNode->next = NULL;
    newNode->number = number;

    return newNode;
}

int main( int argc, const char * arg[] )
{
    NODE * start = NULL, * current, *next;
    char goOn;
    int listSize = 0, number;

    do {
        printf( "List has %d nodes. Enter another number (0 to exit the prompt)\n", listSize );
        scanf("%d", &number );
        if ( number ) {
            if ( !start ) {
                start = createNode( number );
                listSize++;
            } else {
                current = start;
                while ( current->next ) {
                    current = current->next;
                }
                current->next = createNode( number );
                listSize++;
            }
            goOn = 1;
        } else {
            goOn = 0;
        }
    } while ( goOn );

    current = start;
    printf( "List contains the numbers: \n" );
    while (current) {
        printf( "%d", current->number );
        printf( current->next ? ", " : "\n" );
        current = current->next;
    }

    current = start;
    while (current) {
        next = current->next;
        free( current );
        current = next;
    }

    char *answer;
    do {
    printf("Do you want to delete element(s) of the list?");
    scanf("%s", answer);
    }while(answer != "Y" || answer != "N");
    return 0;
}

Upvotes: 0

Views: 218

Answers (1)

Barmar
Barmar

Reputation: 781592

You're declaring a pointer, but not allocating any memory for it.

You're also using == to compare strings. You have to use strcmp() for this.

There's no need to use a string here. Use a single character. And the correct condition operator is &&, not || (see Why non-equality check of one variable against many values always returns true?).

char answer;
do {
    printf("Do you want to delete element(s) of the list?");
    scanf(" %c", &answer);
}while(answer != 'Y' && answer != 'N');

Upvotes: 3

Related Questions