문제

나는 똑 바른 C 초보자이지만, 이것은 나를 괴롭 혔습니다. 연습을 위해 링크 된 목록 구현을 작업하고 있으며 split_node 함수에 변수를 추가하여 segfault를 받고 있습니다.

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

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.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 <Address 0x8b000000 out of bounds>}) 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

변수 정의를 추가하면 SEGFAULT가 발생하는 이유는 무엇입니까? 새로 생성 된 노드의 컨텐츠 포인터를 분쇄하는 것으로 보입니다. 나는 혼란스러워한다. 도움이 있습니까?

도움이 되었습니까?

해결책

Malloc 사용 노드를 동적으로 할당해야합니다.

가지고 있듯이 새 노드는 스택에 선언됩니다. 분할 함수가 반환되면 해당 새 노드는 더 이상 유효한 메모리가 아닙니다.

변수를 추가하면 변수가 스택의 레이아웃이 변경되어 함수가 반환 될 때 약간 다른 동작이 발생하기 때문에 SEGFAULT가 발생합니다.

다른 팁

노드 하위 속성을 NULL로 설정해보십시오. C는 자동으로 메모리를 제로 제로하지 않으므로 아이에 쓰레기가있을 수 있습니다 (또는 Malloc 대신 Calloc을 사용할 수 있음). Soapbox의 대답도 정확합니다.

Valgrind 이러한 유형의 문제를 찾는 데 도움이되는 훌륭한 도구입니다. 명령 줄에서 "Valgrind MyAppName"을 수행 할 수 있으며 이러한 유형의 오류에 대한 세부 정보가 제공됩니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top