c语言 - malloc() 中的访问冲突



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

这是我的代码:

节点.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 

节点.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;
}

测试.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.

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

更改此设置:

(*headRef)->next = newNode;

对此:

*headRef = newNode;

相关内容

  • 没有找到相关文章

最新更新