Search code examples
cpointersexceptionlinked-listnullptr

Why Does this particular code throw an exeption?


Critical error detected c0000374

#pragma once

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

void print_nodes(node* list) {
node *current = (node*)malloc(sizeof(node));
//current->value = 0;
current->next = list;

while (current->next != nullptr) {
    printf("%i\n", current->next->value); <-THROW an Exception in the Fist loop
    current->next = current->next->next;
}
free(current);
}

void add_node(node* list) {

}

inline void new_nodes(node* list, size_t anzahl) {
list[0].before = NULL;
for (int i = 0; i <= anzahl; i++) {
    list[i].value = i + 1;
    list[i].next = &list[i + 1];
    list[i + 1].next = &list[i - 1];
}
list[anzahl].next = NULL;
}

The printf statement Throws an Exception ... but only sometimes. My cpp calls the function new_nodes with the size_t = 10 so it cant be tooooo big.

Additional Info one time even the heap "broke".

Thanks for your Help.


Solution

  • this:

    void print_nodes(node* list) 
    {
        node *current = (node*)malloc(sizeof(node));
        //current->value = 0;
        current->next = list;
    
        while (current->next != nullptr) 
        {
            printf("%i\n", current->next->value); <-THROW an Exception in the Fist loop
            current->next = current->next->next;
        }
        free(current);
    }
    

    Needs to be heavily modified: Suggest:

    modified (after clarification by the OP) to use a 'headless' linked list

    void print_nodes(node* list) 
    { 
        node * current = list; 
    
        while (current) 
        { 
            printf("%i\n", current->value); 
            current = current->next; 
        } 
    }