2012-11-08 88 views
3

我试图为我的大学课程实现链表数据结构,但是在执行代码时,以下行会产生EXC_BAD_ACCESS(code = 1,address = 0x8)错误。malloc()在Xcode中导致EXC_BAD_ACCESS错误

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

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

回答

2

create()功能temp内部for循环的第一次迭代是NULL,然后解除引用导致故障(未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. */ 
    } 
    
+0

如果'temphead'不是'NULL',然后在'temp = temphead'赋值,Xcode吐出一个警告:_Variable'temphead'在这里使用时未初始化,程序停在'malloc()'行。说'线程1:断点1.1' 我不明白。这似乎在大学的Fedora中起作用。我现在做错了什么? 哦,我也实现了你的其他观点。 – vigneshwerv

+0

没关系,我在分配'temp = temphead'之前将内存分配给'temphead'。该程序现在工作得很好。谢谢。 – vigneshwerv