首页 > 解决方案 > c编程链接列表分段错误

问题描述

出于某种原因,我的代码在运行 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;
}

标签: cstructlinked-listsegmentation-fault

解决方案


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


推荐阅读