1

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

1 Answer 1

4

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Note that when you free your node later, you'll need to first free that value.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.