Abhishek Gangwar
Abhishek Gangwar

Reputation: 1767

Error while initializing the structure values

I have just started using pointers.So please bear with me if this looks silly But I am not able to find the reason. I have a structure

typedef struct Intermediatenode
{
    int key;
    char *value;
    int height;
    struct node *next[SKIPLIST_MAX_HEIGHT];
} node;

And I wand to create a new node by using below function

 node *create_node(int key, char * val, int h)
 {
        node *newnode;
        newnode=malloc(sizeof(node));
        newnode->height=h;
        newnode->key=key;
        printf("till here %s \n",val);
        printf("till here %d \n",newnode->height);
        printf("till here %d \n",newnode->key);
        strcpy(newnode->value,val);
        printf("till here %s \n",newnode->value);
        return newnode;
 }

But I Am getting segmentation fault at this "strcpy(newnode->value,val);" Can you please help me with that.Thanks a lot

Upvotes: 1

Views: 32

Answers (1)

paddy
paddy

Reputation: 63471

You allocated memory for the node, but not the string in value. The strcpy function will copy bytes but not allocate memory. It assumes that you've already arranged that. In a pinch, you can allocate and copy the string with strdup:

newnode->value = strdup(val);

Upvotes: 4

Related Questions