我可以传递一个指针变量的 COPY 吗?

Can I pass COPY of a variable that it's a pointer?

我是 C 编程的新手,遇到以下问题。

我有一个 char * 可以存储一个包含任意数量字符的字符串,我正在将这个字符串添加到队列中。然后我想向该队列添加更多字符串,所以我编写了以下代码: (我正在从二进制文件中读取字符串)

char *follower;

while (n!=0) {
    
    follower = (char *) malloc(sizeof(char));    

    /*
       ... Code where I fill follower string using reallocs etc ...
    */

    QUEUE_add(follower);

    free(follower);
}

当我尝试编译它时,我注意到队列总是空的,因为我在 QUEUE_add 之后写了 free。我写它是为了重新使用 follower 变量来填充队列。

如何“发送”follower 存储内容的副本以便将其正确添加到队列中?

如果您正在存储指针并在之后释放它,您将无法访问该内存以及存储在那里的内容。

请记住,如果您只是将指针分配给一个新指针,您只是让新指针指向相同的内存位置,如果您释放一个,则释放另一个,使其悬空。

例如:

char *ptr = calloc(20, sizeof *ptr); //memory for string
char *ptr2 = ptr; //assing ptr to ptr2
free(ptr2); //the memory allocated for ptr2 and ptr is freed, ptr is now a dangling pointer

要重用指针,您需要先用 strcpymemcpy 之类的内容复制 follower 指向的数据。


用法示例:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
    char dest[2][30]; // final container for the string
    
    char *ptr = calloc(20, sizeof *ptr); //memory for string

    char *my_str = "This is my string"; //test string
    
    memcpy(ptr, my_str, 20); //copying string to the memory pointed by ptr for test purposes

    memcpy(dest[0], ptr, sizeof *dest); //copying string to the destination container

    char *other_string = "This is my other string"; //other string to store

    ptr = realloc(ptr, 25); //reallocating ptr capacity to store the other string

    memcpy(ptr, other_string, 25);  //storing the  other string in ptr for example purposes

    memcpy(dest[1], ptr, sizeof *dest); //copying other string to its destination

    free(ptr); //freeing ptr when it's no longer needed

    printf("%s\n%s", dest[0], dest[1]); //test print
}

这是一个简化的例子,不用说,你应该经常测试callocrealloc的return值,以确保内存分配成功。


旁注:

follower = (char *) malloc(sizeof(char));  

不要投射 malloc,它隐藏了 #include <stdlib.h> 的潜在失败,这是声明 malloc 的地方。