Hi I am facing a fragmentation error while executing this code? Can someone explain why?

Posted by aks on Stack Overflow See other posts from Stack Overflow or by aks
Published on 2010-05-04T10:29:23Z Indexed on 2010/05/04 10:48 UTC
Read the original article Hit count: 237

Filed under:
#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;
    }
}

When i execute this code and enters the IP address for the first node, i am facing fragmentation error. The code crashed. Can someone enlighten?

© Stack Overflow or respective owner

Related posts about c