【问题标题】:Segmentation Fault with linked list node assignment in C++C++中链表节点分配的分段错误
【发布时间】:2013-10-15 19:15:34
【问题描述】:

我可能又错过了一些非常简单的东西,但是在实验室里呆了太多时间让我看不出我在这里做错了什么。我正在尝试通过创建一个列表并将新节点附加到它作为从文件中读取的所有字符的链接列表,因为新字符被读入直到文件末尾。

首先是一些背景知识,这里是节点结构的代码:

typedef struct node
{
//each node holds a single character
char data;
//pointer to the next node in the list
struct node *next;
}node;

通过使用几个 printf 语句,我设法将问题缩小到此代码块中的某个位置。

FILE *infile = fopen("data.txt", "r");

int c;
int counter = 0;
node *head, *current = NULL;

//Get the count of our original rules and create the list
do{

   node *item = new node();

  c = fgetc(infile);      

  if(c == '\n'){
counter ++;
  }

  printf("From infile: %c \n", c);

item->data = c; 
item->next = NULL;

printf("Item data: %c", item->data);

if (head == NULL){
  head  = current =  item;
}
else {    
  current->next = item;
  current = item;
}

}while( c != EOF);

我不确定它在哪里,但我知道它在里面。如果我能得到另一双眼睛指出哪里出了问题,我将不胜感激。

【问题讨论】:

    标签: c++ linked-list segmentation-fault


    【解决方案1】:

    你没有在这里初始化head

    node *head, *current = NULL;
    

    所以它会有一个不确定的值,所以这个检查很可能是失败的:

    if (head == NULL){
    

    因此 headcurrent 都不会被正确初始化。

    如果您使用的是C++11,那么您应该使用nullptr 而不是NULL

    【讨论】:

    • 这是 c++ 理想情况下我们应该使用nullptr
    • @Mgetz 理想情况下,我们不应该使用fgetcprintfFILE*、裸指针和冗余structs ;)
    • 就是这样!谢谢!唷,如果我错过了,可能是时候休息一下了。
    猜你喜欢
    • 1970-01-01
    • 2020-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-21
    相关资源
    最近更新 更多