2

I've posted my first attempt at a linked list code below. The objective is to get a linked list of 10 integers and to traverse the list to double the odd numbers and half the even ones. As I'm new to linked lists I'm just currently working on the first part: Generating the list.

From the examples I've seen it looks ok to me. It compiles fine but when I go to run it I get the following error message: "Exception thrown: read access violation. B was 0xCDCDCDCD." This is on the line that says "C=B->next".

Does anyone know what this means and/or why it is occurring? Any input would be appreciated :)

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

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

void freeList(struct node* head);

int main(void)
{
    srand(time(NULL));


    struct node * A = NULL;
    A = malloc(sizeof(struct node));
    struct node* B = malloc(sizeof(struct node));
    struct node* C = malloc(sizeof(struct node));
    struct node* D = malloc(sizeof(struct node));
    struct node* E = malloc(sizeof(struct node));
    struct node* F = malloc(sizeof(struct node));
    struct node* G = malloc(sizeof(struct node));
    struct node* H = malloc(sizeof(struct node));
    struct node* I = malloc(sizeof(struct node));
    struct node* J = malloc(sizeof(struct node));

    A->data = (rand() % 10) + 1;
    B->data = (rand() % 10) + 1;
    C->data = (rand() % 10) + 1;
    D->data = (rand() % 10) + 1;
    E->data = (rand() % 10) + 1;
    F->data = (rand() % 10) + 1;
    G->data = (rand() % 10) + 1;
    H->data = (rand() % 10) + 1;
    I->data = (rand() % 10) + 1;
    J->data = (rand() % 10) + 1;

    B = A->next;
    C = B->next;
    D = C->next;
    E = D->next;
    F = E->next;
    G = F->next;
    H = G->next;
    I = H->next;
    J = I->next;
    J->next = NULL;

    struct node* current = A;
    while (current != NULL)
    {
        printf("%d-->", current->data);
        current = current->next;
    }

    freeList(A);

    return 0; 
}

void freeList(struct node* A)
{ 
    struct node* temp;

    while (A != NULL)
    {
        temp = A;
        A = A->next;
        free(temp);
    }

}
Ollie Parsons
  • 35
  • 1
  • 9

2 Answers2

4

Here's your problem

B = A->next;

You never assigned a value to A->next, so it is uninitialized. The runtime environment filled the memory pointed to by A with 0xCDCDCDCD on allocation, to help you spot that it wasn't initialized. The line of code above reads the uninitialized value of A->next and stores it in B. This is not a valid pointer address! The next line of code C = B->next; throws an exception when you try to dereference the invalid pointer B.

Perhaps you meant to write A->next = B; instead?

Tim Randall
  • 4,040
  • 1
  • 17
  • 39
3

You should assign the nodes to the next pointers, not the other way around. This is how the nodes become linked.

A->next = B;
B->next = C;
. 
.
. 
machine_1
  • 4,266
  • 2
  • 21
  • 42