【问题标题】:why does it show segmentation error in my code?为什么它在我的代码中显示分段错误?
【发布时间】:2021-12-28 18:24:24
【问题描述】:

这是将两个字符串打印在一起的代码,但每当我尝试运行它时,都会出现分段错误,但它编译时没有任何错误,有人可以帮忙吗?

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

typedef struct node
{
    char *data; //string data in this node
    struct node *next; //next node or NULL if none
} Node;
void print(Node *head); //function prototype print
Node *push_node(Node x, Node *strlist);
int main ()
{
    Node node1;
    Node node2;
    Node *list = NULL;
    strcpy(node1.data, "world");
    push_node(node1, list);
    strcpy(node2.data, "hello");
    push_node(node2, list);
    print(list);
return 0;
}
void print(Node *head)
{
    Node *p = head;
    while (p != NULL)
    {
        printf("%s", p->data);
        p = p->next;
    }
}
Node *push_node(Node x, Node *strlist)
{
    x.next= strlist;
    return &x;
}

【问题讨论】:

  • 你没有为node1.data分配任何空间——它只是复制到一个未初始化的指针。
  • 您是否尝试过在调试器中逐行运行代码,同时监控所有变量的值,以确定您的程序在哪个点停止按预期运行?如果您没有尝试过,那么您可能想阅读以下内容:What is a debugger and how can it help me diagnose problems? 您可能还想阅读以下内容:How to debug small programs?
  • 请查看编译器警告。还有returning the address of a local variablereturn &amp;x; 的罪行
  • 基本上你对如何在 C 语言中使用指针有很多困惑。你需要查看你的教学材料,所以不是辅导服务。

标签: c linked-list undefined-behavior singly-linked-list strcpy


【解决方案1】:

你声明了两个节点类型的对象

Node node1;
Node node2;

未初始化的数据成员。那就是对象的指针data有不确定的值。

所以调用函数strcpy

strcpy(node1.data, "world");
strcpy(node2.data, "hello");

导致未定义的行为。

此外,指针list 没有在程序中更改。它在初始化时始终等于NULL。所以调用函数print没有意义。

要使您的代码至少可以正常工作,您需要进行以下更改。

Node *push_node(Node *x, Node *strlist);

//...

node1.data = "world";
list = push_node( &node1, list);
node2.data = "hello";
list = push_node( &node2, list);
print(list);

//...

Node *push_node(Node *x, Node *strlist)
{
    x->next= strlist;
    return x;
}

【讨论】:

    猜你喜欢
    • 2020-02-27
    • 2017-11-25
    • 1970-01-01
    • 2016-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多