Frage

typedef struct mensagem
{
    int sender ;
    int receiver ;
    char *text ;
} *Item ;


typedef struct node 
{
    Item item ;
    struct node *next ;
} *link ;

link init(char* text)
{
    link x = (link) malloc(sizeof(struct node));
    (x->item->text) = (char*) malloc(sizeof(char)*(strlen(text)+1));
    strcpy(x->item->text, text);
    x->next = NULL;
    return x;
}

I meant to use the data inside item, but I get a Segmentation Fault on the line:

(x->item->text) = (char*) malloc(sizeof(char)*(strlen(text)+1));

I'm fairly new to C and pointers, but I can't find the problem here.

War es hilfreich?

Lösung 2

Put this after allocating memory for x:

x->item = malloc(sizeof(struct mensagem));

You have to allocate the memory for the field 'item' before you can actually access and allocate its fields.

Andere Tipps

You haven't allocated memory for the structure pointed to by x->item. Add

x->item = malloc(sizeof (struct mensamam));

before the other malloc.

This should do just fine:

typedef struct mensagem
{
    int sender ;
    int receiver ;
    char *text ;
} Item ;


typedef struct node 
{
    Item *item ;
    struct node *next ;
} Link ;

Link *init(char *text)
{
    // Note: Do error checking after each of these lines in case malloc() fails!
    Link *x = malloc(sizeof(Link));
    x->item = malloc(sizeof(Item));
    x->item->text = malloc(sizeof(char) * (strlen(text) + 1));

    strcpy(x->item->text, text);
    x->next = NULL;
    return x;
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top