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);
}
}