1

I am trying to copy a string from one char * to another, and do not know why the copy does not work.

I am writing a linked list program -- Linklist -- and there are two char * pointers involved. Each points to a struct Node as follows:

struct Node
{
    char * message;
    char * text;
    struct Node * next;
};

typedef struct Node * Linklist;

I have written a function which has two parameters to create a new LinkNode:

Linklist create(char *message,char * text)
{
    Linklist list =(Linklist)malloc(sizeof(struct Node));
    //the message changes after the sentence but text is right.
    if(list==NULL) printf("error:malloc"); 
    list->message=message;
    list->text=text;
    return list;
}

In main:

char *message is"helloworld"

char *text is"test"

I watched the message in gdb,after malloc. The message changed to "/21F/002", but text is still "test"

I added const before message, but it doesn't work.

Can anyone can tell what is happening?

Thanks.

7
  • Is there more to this? What other setup is there in the function itself?
    – sean
    Jul 7, 2012 at 16:33
  • How are you calling create?
    – Kevin
    Jul 7, 2012 at 16:33
  • @MoatazElmasry that is in the original question
    – Hogan
    Jul 7, 2012 at 16:33
  • ok I add more details , it's really strange Jul 7, 2012 at 16:35
  • oh I see. so using this malloc statement you are defining a list with exactly one Node, right? Jul 7, 2012 at 16:36

2 Answers 2

4

The problem is that strings in c don't work the same way. Here is how you copy a string:

Linklist create(char *message,char * text)
{
    Linklist list =(Linklist)malloc(sizeof(struct Node));
    //the message changes after the sentence but text is right.
    if(list==NULL) printf("error:malloc"); 

    list->message = malloc(strlen(message)+1);
    if(list->message==NULL) printf("error:malloc"); 
    strcpy(list->message,message);

    list->text = malloc(strlen(text)+1);
    if(list->text==NULL) printf("error:malloc"); 
    strcpy(list->text,text);

    return list;
}

Of course you have to be careful here, make sure message and text are not coming from the user or you risk buffer overflow vulnerabilities.

You can use strncpy() to solve that issue.

2

you must allocate the storage for your pointers message and text and then copy the string.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.