Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.
like image 222
Saleh Omar Avatar asked Dec 18 '25 01:12

Saleh Omar


1 Answers

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

Change this:

(*headRef)->next = newNode;

To this:

*headRef = newNode;
like image 143
WhozCraig Avatar answered Dec 20 '25 18:12

WhozCraig



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!