Organizational Research By

Surprising Reserch Topic

Experts Most Trusted Topic


segfault while printing linked list after stack clear


segfault while printing linked list after stack clear  using -'c,linked-list'

To be more specific, this code is supposed to be a lesser clone of the Unix function dc. The linked list seems to be working fine. If I attempt to use c to clear the memory, add more numbers, then print again with f I get a segfault. It seems to be printing what should be the Null Node in the linked list.

Interaction:
$ ./test
1 2 3
f
3
2
1
c
4 5
f
5
4
0
Segmentation Fault


Here's the code itself:

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

struct Node{
  int val;
  struct Node *next;
};

void cons_node(struct Node **head, int num)
{
  struct Node *newNode = malloc(sizeof(struct Node));
  newNode->val = num;
  newNode->next = NULL;
  if (*head == NULL){
    *head = newNode;
  }
  else {
    newNode->next = *head;
    *head = newNode;
  }
}


I'm assuming the problem lies here in the display func:

void display_list(struct Node *head)
{
  struct Node *current = head;
  while(current != NULL)
    {
      printf("%d\n", current->val);
      current = current->next;}

}

void print_top(struct Node *head)
{
  printf("%d\n", head->val);
}


or here in the clear func:

void clear_stack(struct Node *head)
{
  struct Node *current;
  while ((current = head)!= NULL) {
    head = head->next;
    free(current);
  }
}

void vorpal_func(struct Node *head)
{
  struct Node *current;
  current = head;
  free(current);
}
int main(){

  int input;
  int first = 1;
  char quit = 'n';
  char inputchar = ' ';

  struct Node *head = NULL;

  while (quit == 'n'){

    if (scanf("%d", &input) == 1){
      cons_node(&head, input);
      first = 0;
    }

    else{
      inputchar = getchar();

      if(first == 1)
    printf("List is empty\n");

      else{
    switch (inputchar){
    case 'q':
      quit = 'y';
      break;
    case 'E':
      quit = 'y';
      break;
    case 'f':
      display_list(head);
      break;
    case 'p':
      print_top(head);
      break;
    case 'c':
      clear_stack(head);
      first = 1;
      break;
    case 't':
      vorpal_func(head);
      break;
    }
      }
    }
  }

  return 0;
}


I've been attempting to figure out the problem for a few hours now. Any tips?
    

asked Sep 9, 2015 by LottieFreder
0 votes
10 views



Related Hot Questions



Government Jobs Opening


...