user3697730
user3697730

Reputation: 251

segmentation fault when using pointer to pointer

I had been trying to use a pointer to pointer in a function,but is seems that I am not doing the memory allocation correctly... My code is:

#include<stdio.h>
#include<math.h>
#include<ctype.h>
#include<stdlib.h>
#include<string.h>


struct list{
       int data;
       struct list *next;
};

void abc (struct list **l,struct list **l2)
{
     *l2=NULL;
     l2=(struct list**)malloc( sizeof(struct list*));
     (*l)->data=12;
     printf("%d",(*l)->data);
     (*l2)->next=*l2;
 }

 int main()
 {
     struct list *l,*l2;
     abc(&l,&l2);
     system("pause");
     return(0);
 }

This code compiles,but I cannot run the program..I get a segmentation fault..What should I do?Any help would be appreciated!

Upvotes: 1

Views: 91

Answers (3)

user3386109
user3386109

Reputation: 34829

Note that l and l2 are declared as pointers in main, and neither one is initialized to point to anything. So you have two choices, either initialize the pointers in main and then use them in abc, or initialize the pointers in abc.

Based on what you've written, it seems that you want to initialize in abc. To do that you must malloc enough memory to hold the struct list and then set the pointer to point to that memory. The resulting abc function looks like this

void abc( struct list **l, struct list **l2 )
{
    *l  = malloc( sizeof(struct list) );
    *l2 = malloc( sizeof(struct list) );

    if ( l == NULL || l2 == NULL )
    {
        fprintf( stderr, "out of memory\n" );
        exit( 1 );
    }

    (*l)->data = 12;
    (*l)->next = *l2;

    (*l2)->data = 34;
    (*l2)->next = NULL;

    printf( "%d %d\n", (*l)->data, (*l2)->data );
}

Upvotes: 2

Andrei Bozantan
Andrei Bozantan

Reputation: 3921

The crash is due to (*l)->data=12; since (*l) is actually an unitialized varaible.

Upvotes: 1

user4815162342
user4815162342

Reputation: 154906

This part is incorrect:

 l2=(struct list**)malloc( sizeof(struct list*));
 (*l)->data=12;

You cannot assign to a structure that you didn't allocate. The correct code would be something along the lines of:

 *l = malloc(sizeof(struct list));
 (*l)->data = 12;

Upvotes: 0

Related Questions