gpt4 book ai didi

c - malloc() 中的访问冲突

转载 作者:行者123 更新时间:2023-12-04 10:45:40 26 4
gpt4 key购买 nike

我正在使用 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;

关于c - malloc() 中的访问冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22266907/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com