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

标签 c pointers malloc

我正在尝试将一个字符串从一个 char * 复制到另一个,但不知道为什么复制不起作用。

我正在编写一个链表程序 -- Linklist -- 涉及到两个 char * 指针。每个都指向一个struct Node,如下所示:

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

typedef struct Node * Linklist;

我写了一个函数,它有两个参数来创建一个新的 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;
}

主要内容:

字符 *消息是"helloworld"

char *text 是"test"

我在 gdb 中看到消息,在 malloc 之后。消息变为“/21F/002”,但文本仍为“test”

我在消息前添加了 const,但它不起作用。

谁能告诉我发生了什么?

谢谢。

最佳答案

问题是 c 中的字符串的工作方式不同。以下是复制字符串的方法:

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;
}

当然,您在这里必须小心,确保消息和文本不是来自用户,否则您将面临缓冲区溢出漏洞的风险。

您可以使用 strncpy() 来解决该问题。

关于c - 为什么两个字符指针之间的字符串复制不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11376758/

相关文章:

c - 使用 malloc() 分配内存块

linux - 是否有 malloc 变体在调用 `free()` 时将 block 清零?

c - 免费(): invalid next size (fast) error

c - valgrind : Conditional jump or move depends on uninitialised value using strlen() strncat()

c++ - QtCreator CMake 项目 - 如何显示所有项目文件

c - 尝试从 char*[] 复制所有字符串但出现段错误

c - fread 和 fwrite 有不同的结果

C 函数指针错误

c - 如何警告指向超出范围的局部变量的指针

C: 复制一个 char *指针到另一个