G
G
gosha_tst2018-04-17 18:55:43
C++ / C#
gosha_tst, 2018-04-17 18:55:43

Why Segmentation Fault?

I'm doing a list implementation in C (just for fun). I have two questions: why is the Segmentation fault and how bad is this code?)

#include <stdio.h>

typedef struct Node {
    struct Node* next;
    int value;
} Node;

typedef struct List {
    Node* head;
    Node* list[10];
} List;

void newNode(List* change_list, int value) {
    int size = sizeof(change_list)/sizeof(*change_list);

    if (size == 0) {
        Node* new_node;
        new_node->next = NULL; // здесь
        new_node->value = value; // и здесь вываливается ошибка
        change_list->list[size] = new_node;
        change_list->head = change_list->list[0];
    }
}

void main() {
    List* new_list;
    newNode(new_list, 5);
    printf("%d", new_list->list[0]->value);
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman, 2018-04-17
@gosha_tst

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

typedef struct Node {
    struct Node* next;
    int value;
} Node;

typedef struct List {
    Node* head;
    Node* list[10];
} List;

void newNode(List* change_list, int value) {
    int size = sizeof(change_list)/sizeof(*change_list);

    if (size == 0) {
        Node* new_node = (Node*)malloc(sizeof(Node));
        new_node->next = NULL; // здесь
        new_node->value = value; // и здесь вываливается ошибка
        change_list->list[size] = new_node;
        change_list->head = change_list->list[0];
    }
}

int main() {
    List* new_list = (List*)malloc(sizeof(List));
    newNode(new_list, 5);
    printf("%d", new_list->list[0]->value);
}

https://ru.stackoverflow.com/questions/245369/Qu...
also free() on the List and
each node will need to be called.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question