1

Программа компилируется, но при запуске появляется ошибка "Прекращена работа программы"

Только начала погружаться в эту тему и никак не могу понять, в чём ошибка :(

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

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

typedef struct List
{
    node_t *head;
    int size;
} list_t;

void
init (list_t *l)
{
    l->head = NULL;
    l->size = 0;
}

void 
push_back (list_t *l, int value)
{
    node_t *cur = l->head;
    while (cur->next != NULL) cur = cur->next;
    node_t *tmp = (node_t*) malloc (sizeof (node_t));
    tmp->value = value;
    tmp->next = NULL;
    cur->next = tmp;
    l->size++;
}

void
print_list (list_t *l)
{
    node_t *cur = l->head;
    while (cur != NULL)
    {
        printf("%d", cur->value);
        cur = cur->next;
    }
}

void 
destroy (list_t *l)
{
    node_t *cur = l->head;
    node_t *tmp;
    while (cur != NULL)
    {
        tmp = cur;
        cur = cur->next;
        free (tmp);
    }
}

int 
main ()
{
    int x = 1, y = 2;
    list_t *l = NULL;
    init (l);
    push_back (l, x);
    push_back (l, y);
    print_list (l);
    destroy (l);
    return 0;
}
3
  • Ну так написан бред: в функцию init передается null-указатель, а затем через этот null-указатель что-то пытаются писать. Ну все и падает. Что вы хотели этим сказать? 17 дек 2017 в 2:17
  • какое тогда начальное значение l должно быть?
    – seiganso
    17 дек 2017 в 2:21
  • list_t *l = (list_t*) malloc (sizeof (list_t));
    – user176262
    17 дек 2017 в 3:01

1 ответ 1

2

Я малость изменил ваш код, сейчас он выглядит по-людски :D

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

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

Node *initNode(int value)
{
    Node *res = (Node*)malloc(sizeof(Node));
    res->value = value;
    res->next = NULL;
    return res;
}

typedef struct list
{
    Node* head;
    int size;
} List;

List *initList()
{
    List* _list = (List*)malloc(sizeof(List));
    _list->head = NULL;
    _list->size = 0;
    return _list;
}
// Использую рекурсию, чтобы удалять Nodes | можно написать свою версию с линейным удалением (оно в вашем коде, но так красивее и вероятность ошибки меньше)
void deleteNodes(Node* _node)
{
    if (_node!=NULL)
        deleteNodes(_node->next);
    else
        return;
    printf("\nI'm going to delete Node with value = %d, located in %d", _node->value, _node);
    free(_node);
}

void deleteList(List* _list)
{
    deleteNodes(_list->head);
    free(_list);
}

void pushToList(List* _list, int value)
{
    _list->size++;
    // Голова листа изначально указывает на NULL, а после первого пуша начинает уже на новый элемент
    if (_list->head == NULL)
    {
        _list->head = initNode(value);
        return;
    }

    Node* head = _list->head;
    Node* prev = NULL;
    while (head != NULL)
    {
        prev = head;
        head = head->next;
    }
    head = initNode(value);
    prev->next = head;
}

void printList(List* _list)
{
    Node *cur = _list->head;
    while (cur != NULL)
    {
        printf("%d ", cur->value);
        cur = cur->next;
    }
}

int main()
{
    List* _list = initList();
    for (int i = 0;i<10;i++)
        pushToList(_list, i);
    printList(_list);
    deleteList(_list);
}

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.