malloc中的访问冲突()

时间:2014-03-08 08:18:46

标签: c visual-studio-2010 malloc

我正在使用C和Visual Studio 2010编写链接列表的示例代码

这是我的代码:

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

每当我运行程序时,Push()函数内会抛出异常,并显示以下消息:

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

1 个答案:

答案 0 :(得分:2)

您在初始插入的第一种情况下取​​消引用空指针。

改变这个:

(*headRef)->next = newNode;

对此:

*headRef = newNode;