如何在c中为链表中的结构分配内存?
我编写这些结构和函数是为了向链表添加一个链接,但我遇到了分段错误。为什么会这样如何在c中为链表中的结构分配内存?,c,segmentation-fault,C,Segmentation Fault,我编写这些结构和函数是为了向链表添加一个链接,但我遇到了分段错误。为什么会这样 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
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;
}
我认为问题在于日期结构的内存分配,但不确定。您正在迭代
temp
,直到它等于NULL
,然后您正在取消对它的引用。while循环的条件应该是temp->next!=NULL
请不要强制转换malloc
的返回值。他不是,但在那里定义他的临时指针让我感觉很糟糕。混合使用初始化变量声明和未初始化变量声明已经不太确定,但在函数入口仅在非常小的子作用域中声明变量更糟糕。此外,如果(entry==NULL | | entry->date==NULL),不要编写if
如果一个人成功地失去了自由,那么他将无法获得自由,你也将无法再次释放他。不要乱用非空闲内存。@רועיאבין,他为什么不写呢?如果满足第一个条件,则不评估第二个条件;如果第一个失败,则可以安全地评估第二个。有什么问题吗?他的错误是,如果第一次malloc
失败,分配entry->date=
可能会失败。非常感谢!结束循环的条件确实是个问题,因为如果第一个malloc可以工作,而第二个malloc失败,那么他如何知道如何释放第一个malloc?