【问题标题】:Can I pass COPY of a variable that it's a pointer?我可以传递一个变量的副本,它是一个指针吗?
【发布时间】:2020-09-27 17:50:22
【问题描述】:

我是 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 存储的副本以便正确添加到队列中?

【问题讨论】:

  • OT 但你也应该知道 malloc(sizeof(char)) 只分配一个字节,这对于存储字符串没有用,因为它只有字符串终止符的空间(即你只能存储一个空字符串)。此外,根据定义,sizeof(char) 始终为 1,因此您应该改为 malloc(n+1) 其中 n 是您要存储的字符串的最大长度,+1 为字符串终止符提供空间。
  • 我用 malloc 初始化 follower 字符串(也许这是多余的),然后我使用 reallocs 请求更多内存,直到所有字符串都完成。示例中没有写,我的错

标签: c queue dynamic-memory-allocation


【解决方案1】:

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

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

例如

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 &lt;stdlib.h&gt; 的潜在失败,这是malloc 的声明位置。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-04
    • 1970-01-01
    • 2017-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多