2017-02-25 75 views
-1

我写了这些结构和函数来添加链接到链表,但我得到分段错误。为什么会发生?如何为c中的链表中的结构分配内存?

typedef struct primaries_date{ 
    int day; 
    int month; 
    int time; 
} primaries_date; 

typedef struct usa_primaries { 
    primaries_date *date; 
    char *state; 
    int open; 
    struct usa_primaries *next; 
} usa_primaries; 

usa_primaries *head = NULL; 

void insert(int day, int month, int time, char *state, int open){ 
    usa_primaries *temp, *entry = (usa_primaries  *)malloc(sizeof(usa_primaries)); 
    entry->date = (primaries_date *)malloc(sizeof(primaries_date)); 
    if(entry == NULL || entry->date==NULL){ 
     printf("error couldnt allocate memory"); 
     return; 
    } 
    entry->date->day = day; 
    entry->date->month = month; 
    entry->date->time = time; 
    entry->state = state; 
    entry->open = open; 

    if(head ==NULL){ 
     head = entry; 
    } else { 
     temp = head; 
     while(temp!=NULL) 
      temp = temp->next; 
     temp->next = entry; 
    } 
    entry->next = NULL; 
} 

我认为问题是与内存分配的日期结构,但不知道。

+0

请不要强制转换'malloc'的返回值。 – aschepler

+0

他不是,但是定义他的临时指针对我来说不好。将初始化的变量声明与非初始化的变量声明混合已经很简单,但在函数入口声明一个变量时,它只在一个非常小的子范围中变得更糟。 –

回答

2

您正在迭代temp,直到它等于NULL,然后您将对其进行解引用。你的while循环的条件应该是temp->next != NULL

+0

也不要写'if(entry == NULL || entry-> date == NULL)'如果一个人成功地配对,所以他不会得到免费的,你将无法再释放他。不要乱用非自由的记忆。 –

+0

@רועיאבידן,为什么他不应该那样写呢?如果满足第一个条件,则不会评估第二个条件;如果第一次失败,则评估为第二次是安全的。有什么问题吗?他的缺点是,如果第一个'malloc'失败,赋值'entry-> date ='可能会失败。 –

+0

非常感谢!结束循环的条件真的是问题 – tomslu