首页 > 解决方案 > 我可以传递一个变量的副本,它是一个指针吗?

问题描述

我是 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);
}

当我尝试编译这个时,我注意到队列总是空的,因为free我写了 after QUEUE_add。我写它是为了重用follower变量以填满队列。

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

标签: cqueuedynamic-memory-allocation

解决方案


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

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

例如

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

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


使用示例:

#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确保内存分配成功。


边注:

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

不要施放malloc,它隐藏了一个潜在的失败,#include <stdlib.h>malloc是声明的地方。


推荐阅读