gpt4 book ai didi

c - malloc() 在 Xcode 中导致 EXC_BAD_ACCESS 错误

转载 作者:行者123 更新时间:2023-12-02 02:10:06 25 4
gpt4 key购买 nike

我正在尝试为我的大学类(class)实现链表数据结构,但在执行代码时,以下行会产生 EXC_BAD_ACCESS(code=1, address=0x8) 错误。

temp->next = (ptrtonode) malloc(sizeof(struct node));

以下是完整的代码。
#include <stdio.h>
#include <stdlib.h>
typedef struct node *ptrtonode;
typedef ptrtonode header;

struct node
{
int data;
ptrtonode next;
};

ptrtonode create(int n)
{
int i;
header temphead = NULL;
ptrtonode temp = temphead;
for(i=0;i<n;i++)
{
temp->next = (ptrtonode) malloc(sizeof(struct node));
printf("Enter data for node %d: ", i+1);
scanf("%d", &temp->next->data);
temp = temp->next;
}
temp->next = NULL;
return temphead;
}

int main(int argc, const char * argv[])
{
header head;
int n;
printf("How many nodes do you wish to create?");
scanf("%d", &n);
head = create(n);
}

任何帮助,将不胜感激。
谢谢大家!

最佳答案

for 的第一次迭代中在 create() 内循环功能tempNULL ,然后取消引用导致失败(不是 malloc() 导致失败)。您需要稍微重构代码以防止取消引用 NULL指针。

其他要点:

  • 类型转换 malloc() 的返回值不需要。
  • 检查 scanf() 的结果确保n被分配了一个有效的整数(并确认 int 是正数):
    /* scanf() returns the number of assignments made,
    which in this case should be 1. */
    if (1 == scanf("%d", &n) && n > 0)
    {
    /* 'n' assigned a sensible value. */
    }
  • 关于c - malloc() 在 Xcode 中导致 EXC_BAD_ACCESS 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13286892/

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