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

时间:2010-05-04 10:29:24

标签: c

#include<stdio.h>
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地址时,我面临碎片错误。代码崩溃了。有人可以开导吗?

1 个答案:

答案 0 :(得分:2)

ipAddress只是一个未初始化的char指针。您没有分配ipAddress

指向的内存

当你这样做时

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

预计temp1-&gt; 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块。您应该head指向新创建的节点,该节点由temp1而不是temp指向:

if(!temp)
{
  head = temp; // this should be head = temp1;
}
相关问题