简体   繁体   中英

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!

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 );
}

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

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM