简体   繁体   English

为什么两个char指针之间的字符串复制不起作用?

[英]Why doesn't string copy between two char pointers work?

I am trying to copy a string from one char * to another, and do not know why the copy does not work. 我试图将一个字符串从一个char *复制到另一个字符,并且不知道为什么该复制不起作用。

I am writing a linked list program -- Linklist -- and there are two char * pointers involved. 我正在编写一个链接列表程序Linklist并且涉及两个char *指针。 Each points to a struct Node as follows: 每个都指向一个struct Node ,如下所示:

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 : 我编写了一个函数,该函数具有两个参数来创建新的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 *消息是“ helloworld”

char *text is"test" char *文本为“测试”

I watched the message in gdb,after malloc. 我在malloc之后观看了gdb中的消息。 The message changed to "/21F/002", but text is still "test" 消息更改为“ / 21F / 002”,但文本仍为“ test”

I added const before message, but it doesn't work. 我在消息之前添加了const ,但是它不起作用。

Can anyone can tell what is happening? 任何人都可以告诉发生了什么事吗?

Thanks. 谢谢。

The problem is that strings in c don't work the same way. 问题是c中的字符串不能以相同的方式工作。 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. 您可以使用strncpy()解决该问题。

您必须为指针消息和文本分配存储空间,然后复制字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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