c编程链表分割错误

时间:2018-07-10 20:31:46

标签: c struct linked-list segmentation-fault

由于某种原因,我的代码可以在运行ubuntu 16.04的系统上正常运行,但是当我在学校计算机(也运行Ubuntu 16.04)上运行该代码时,会出现分段错误。当我运行调试器时,该行声称它来自最后的打印循环,这是没有意义的,因为int不应触发分段错误。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <ctype.h>

int RETURN = 0; //return value to change if error found

// check if entered value is a number
bool isNumericChar(char x)
{
    return (x >= '0' && x <= '9')? true: false;
}

// Recreated atoi to check for non ints
int myAtoi(char *str)
{
  if (*str == '\0'){
    return 0;
  }

  int res = 0; 
  int sign = 1;
  int i = 0;  

  // If number is negative, then update sign
  if (str[0] == '-'){
    sign = -1;
    i++;  
  }

  // Iterate through all digits of input string and update result
  for (; str[i] != '\0'; ++i){
    if (isNumericChar(str[i]) == false){
      RETURN = 1;
      fprintf(stderr, "must be integer\n");
      break;
      return 0;
    }
    res = res*10 + str[i] - '0';
  }

    // Return result with sign
  return sign*res;
}

// this is main struct of a node of the linked list
struct LL {
  int number;
  struct LL *next;
};

// this function allocates memory for a node and returns the
// allcoated node item
struct LL *makeNode(int num) {
  struct LL *node = (struct LL *) malloc( sizeof(struct LL) );
  node->number = num;
  return node;
}

int main() {
  char input[10];   
  struct LL * stack_head; 
  bool wasPush = false; 
  int num = 0; 
  while(EOF != scanf("%s", input )) {
    if( 0 == strcmp(input, "push") ) {   // if the word is push, then next item may be a number
      wasPush = true;
    } 
    else if( 0 == strcmp( input, "pop" ) ) { 
      wasPush = false; 
      if( stack_head != NULL ) {
        stack_head = stack_head->next;   
      }
    } 
    else{
      // probably a number
      if( !wasPush ){
        continue;   // and last word was a push
      }
      int number = myAtoi(input);   //convert this to a number

      if( stack_head == NULL ) {   //an empty linked list then this is the first node
        stack_head = makeNode(number);
        stack_head->next = NULL;
      }
      else{   // list and can have a next item in it
        struct LL * prev_head = stack_head;
        stack_head = makeNode(number);
        stack_head->next = prev_head;
      }
      wasPush = false;
    }
  }

  // we print the items on the stack now by iterating
  // from the top to the bottom of the stack
  while( stack_head != NULL ) {
    num = stack_head->number;
    printf("%d\n", num );
    stack_head = stack_head->next;
  }
  return RETURN;
}

1 个答案:

答案 0 :(得分:4)

尝试将stack_head初始化为NULL。不能保证局部变量会被初始化,因此您的stack_head == NULL检查可能会失败。