【问题标题】:Printing a linked-list causes segmentation fault in C program打印链表会导致 C 程序中的分段错误
【发布时间】:2013-10-09 20:33:43
【问题描述】:

下面的代码应该是根据用户输入创建一个链表并显示它,但是显示函数会导致分段错误。

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

struct node{
  int value;
  struct node *next;
};

struct node* createLinkedList()
{
  char string[6];
  char string2[6] = "exit";
  struct node* head;
  struct node* prev;
  struct node temp;
  head = &temp;
  prev = &temp;
  prev->next = NULL;
  printf("Enter the first number\n");
  scanf("%s",string);   
  if(strcmp(string,string2)!=0){
    prev->value=atoi(string);
  }
  while(strcmp(string,string2)!=0){
    printf("Enter the next number\n");
    scanf("%s",string); 
    if(strcmp(string,string2)!=0){
      prev->next=(struct node *)malloc(sizeof(struct node));
      prev->next->next=NULL;
      prev->next->value=atoi(string);       
      prev = prev->next;
    }
    else{
      break;
    }
  }
  return head;
}

void printLinkedList(struct node* head){
  struct node* current = head;
  while(current!=NULL){
    printf("%d -> ",current->value);
    current=current->next;
  }
}

int main()
{
  struct node *first;
  first = createLinkedList();
  printLinkedList(first);
  return(0);
}

这里是调试信息:

Enter the first number
1
Enter the next number
2
Enter the next number
3
Enter the next number
4
Enter the next number
exit

Program received signal SIGSEGV, Segmentation fault.
0x0000000000400865 in printLinkedList (head=0x7fffffffe150) at linkedList.c:45
45      printf("%d -> ",current->value);

【问题讨论】:

  • 调试器说了什么?
  • 您正在返回createLinkedList中的局部变量的地址
  • 非常感谢 :) @Andreas
  • 谁能推荐一本关于堆和栈内存分配的好书?

标签: c pointers linked-list segmentation-fault


【解决方案1】:

问题出在以下几行:

struct node* head;
struct node* prev;
struct node temp;
head = &temp;
prev = &temp;

因为 temp 是在堆栈上声明的,所以当它超出范围时它会丢失 - 在这种情况下是在函数结束之后。由于您将 temp 的地址分配给 head 和 prev,因此返回的 head 指向垃圾而不是堆栈。

【讨论】:

    【解决方案2】:

    而不是

    struct node temp;
    head = &temp;
    prev = &temp;
    

    应该是

    head =(struct node *)malloc(sizeof(struct node));
    prev = head;
    

    您正在返回存储在堆栈中的本地结构的内存地址。相反,您应该从堆中请求内存来存储头节点并将地址返回给该节点。

    【讨论】:

      猜你喜欢
      • 2015-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-28
      • 2021-01-29
      相关资源
      最近更新 更多