tags:

views:

86

answers:

1
#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?

+2  A: 

ipAddress is just a char pointer which is uninitialized. You've not allocated memory that could be pointed by ipAddress

When you do

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

It is expected that temp1->ipAddress points to a char array, which could be statically or dynamically allocated.

In your case you can change

char *ipAddress;
char *domainName;

to

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

Also after you allocate a new node by doing a malloc you are not initializing the next pointer of the newly created node. You should be doing:

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

Also when the list is initially empty, head will be NULL so the if block will be executed. You should make head point to the newly created node, which is pointed by temp1 not temp:

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