-2

Error in debug: Read access violation current was 0xCDCDCDCD

Please help me

This is the struct

typedef struct node
{
    int data;
    struct node* next;
} node_t;

This is the function for add new data

node_t* push(node_t* head, int data)
{
    node_t* current = (node_t*)malloc(sizeof(node_t));
    current->data = data;
    current->next = head;
    head = current;

    return current;
}

This function print all data of the list

void print_list(node_t* head)
{
    node_t* current = head;

    while (current != NULL)
    {
        printf("Data: %d\n", current->data); // READ ACCESS VIOLATION
        current = current->next;
    }
}

Main of program

int main()
{
    node_t* head = (node_t*)malloc(sizeof(node_t));
    head = push(head, 1);
    head = push(head, 2);
    print_list(head);

    return 0;
}
xjabr
  • 95
  • 1
  • 4
  • 1
    Read this: [In Visual Studio C++, what are the memory allocation representations?](https://stackoverflow.com/questions/127386/in-visual-studio-c-what-are-the-memory-allocation-representations) And consider what `head->next` points to after your *original* allocation in `main()` (that allocation shouldn't even be there; it should be initially `NULL`). Unrelated question, what archaic book are you using that suggests managing memory in C++ with `malloc` and `free` in the first place? – WhozCraig Jul 04 '19 at 19:02

1 Answers1

2

You never initialize the contents of head in main before first use. 0xCDCDCDCD is uninitialized memory, at least under Microsoft compilers and building with _DEBUG defined. So head->next and head->data will be 0xCDCDCDCD in debug mode, and undefined data in a release build.

Instead of initializing head with an uninitialized instance of a node, just use:

node_t* head = NULL;
Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251