Saleh Omar
Saleh Omar

Reputation: 759

Access violation in malloc()

I am writing a sample code for a linked list using C and Visual Studio 2010

Here is my code:

Node.h

#ifndef NODE
#define NODE
#include <stdio.h>
#include <stdlib.h>

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

int Length(struct node* head);
struct node* BuildOneTwoThree();
void Push(struct node** headRef, int newData);
#endif 

Node.c

#include "Node.h"


int Length(struct node* head){

int count = 0;
struct node * current = head;
while(current != NULL){
    count++;
    current = current -> next;
}
return count;
}

void Push(struct node** headRef, int newData){

    //The following line is where the error occures
struct node * newNode = (struct node*)malloc(sizeof(struct node));

newNode->data = newData;
newNode->next = (*headRef);
(*headRef)->next = newNode;

}

struct node* BuildOneTwoThree(){

struct node* list = NULL;
Push(&list,1);
Push(&list,2);
Push(&list,2);

return list;

}

Test.c

#include "Node.h"

void main(){
struct node * current= NULL;

struct node * list = BuildOneTwoThree();

for(current = list; current != NULL; current = current -> next){
    printf("%d",current->data);
}
}

Whenever I run the program an exception is thrown inside the Push() function with the following message:

Unhandled exception at 0x776215ee in LinkedList.exe: 0xC0000005: Access violation writing location 0x00000004.

Upvotes: 3

Views: 1612

Answers (1)

WhozCraig
WhozCraig

Reputation: 66194

You're dereferencing a null pointer in the first case on the initial insert.

Change this:

(*headRef)->next = newNode;

To this:

*headRef = newNode;

Upvotes: 2

Related Questions