当前位置:  开发笔记 > 编程语言 > 正文

Segfault来自添加变量

如何解决《Segfault来自添加变量》经验,为你挑选了1个好方法。

我当然是一个直接的C新手,但这让我很难过.我正在研究实践的链表实现,我只是通过向split_node函数添加一个变量来获得段错误:

#include 
#include 
#include 

struct Node {
    struct Node *child;
    char *content;
};

void print_list(struct Node node);
void split_node(struct Node *node, int position);

int main() {

    struct Node head, second, third;

    head.content = "first";
    second.content = "second";
    third.content = "i'm third";

    head.child = &second;
    second.child = &third;

    print_list(head);
    split_node(&head, 3);
    print_list(head);

    return 0;
}

void print_list(struct Node node) {
    printf("%s\n", node.content);
    if(node.child) print_list(*node.child);
}

    /*
    Split node into two nodes, with the first position characters of the node's content remaining with node, and the remainder being copied to the new node. (It doesn't yet truncate the first node's string, but does do the copy.)
    */
void split_node(struct Node *node, int position) {
    if(position >= strlen((*node).content)) return;
    struct Node newNode;
    newNode.child = (*node).child;
    (*node).child = &newNode;

    int length = (strlen((*node).content) - position);
    newNode.content = malloc(sizeof(char) * (length + 1));
    strncpy(newNode.content, (*node).content + sizeof(char) * position, length);
    newNode.content[length] = '\0';

    //int foo;
}

这段代码编译(gcc -Wall -o list list.c)并且运行正常:

$ ./list
first
second
i'm third
first
st
second
i'm third

但如果我int foo在结束时取消注释split_node,编译并运行,我得到:

$ ./list
first
second
i'm third
first
st
Segmentation fault

gdb给了我这个回溯:

#0  0x91d6ae70 in strlen ()
#1  0x91dd3126 in puts ()
#2  0x00001f21 in print_list (node={child = 0xbcec815b, content = 0x8b000000 
}) at list.c:41 #3 0x00001f3c in print_list (node={child = 0x8fe0154b, content = 0x1ff6 "i'm third"}) at list.c:42 #4 0x00001f3c in print_list (node={child = 0xbffff568, content = 0x1fef "second"}) at list.c:42 #5 0x00001f3c in print_list (node={child = 0xbffff570, content = 0x1fe9 "first"}) at list.c:42 #6 0x00001ee0 in main () at list.c:33

为什么添加变量定义会导致段错误?它似乎粉碎了新创建的节点的内容指针.我糊涂了; 任何帮助?



1> SoapBox..:

您需要动态分配节点(使用malloc).

正如您所拥有的那样,您的新节点将在堆栈中声明.当split函数返回时,该新节点不再是有效内存.

添加变量会导致段错误,因为该变量会更改堆栈的布局,从而导致函数返回时的行为略有不同.

推荐阅读
虎仔球妈_459
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有