执行C程序时出现碎片错误

#include struct table { char *ipAddress; char *domainName; struct table *next; }; struct table *head = NULL; void add_rec(); void show_rec(); int main() { add_rec(); show_rec(); return 0; } void add_rec() { struct table * temp = head; struct table * temp1 = (struct table *)malloc(sizeof(struct table)); if(!temp1) printf("\n Unable to allocate memory \n"); printf("Enter the ip address you want \n"); scanf("%s",temp1->ipAddress); printf("\nEnter the domain name you want \n"); scanf("%s",temp1->domainName); if(!temp) { head = temp; } else { while(temp->next!=NULL) temp = temp->next; temp->next = temp1; } } void show_rec() { struct table * temp = head; if(!temp) printf("\n No entry exists \n"); while(temp!=NULL) { printf("ipAddress = %s\t domainName = %s\n",temp->ipAddress,temp->domainName); temp = temp->next; } } 

当我执行此代码并输入第一个节点的IP地址时,我正面临碎片错误。 代码崩溃了。 有人可以开导吗?

ipAddress只是一个未初始化的char指针。 您没有分配可由ipAddress指向的内存

当你这样做

 scanf("%s",temp1->ipAddress); 

预期temp1-> ipAddress指向一个char数组,可以静态或动态分配。

在你的情况下你可以改变

 char *ipAddress; char *domainName; 

 char ipAddress[16]; // aaa.bbb.ccc.ddd char domainName[MAX_DOMAIN_LEN]; // choose max length suitably. 

在通过执行malloc分配新节点之后,您还没有初始化新创建的节点的next指针。 你应该这样做:

 struct table * temp1 = (struct table *)malloc(sizeof(struct table)); temp1->next = NULL; // this is missing. 

此外,当列表最初为空时, head将为NULL因此将执行if块。 您应该指向新创建的节点,该节点由temp1而不是temp指向:

 if(!temp) { head = temp; // this should be head = temp1; }