【问题标题】:Dynamically allocating memory for const char string using malloc()使用 malloc() 为 const char 字符串动态分配内存
【发布时间】:2014-02-05 14:20:39
【问题描述】:

我正在编写一个程序,它从 .ini 文件中读取一个值,然后将该值传递给一个接受 PCSTR(即 const char *)的函数。函数是getaddrinfo()

所以,我想写PCSTR ReadFromIni()。为了返回一个常量字符串,我计划使用malloc() 分配内存并将内存转换为一个常量字符串。我将能够获得从 .ini 文件中读取的确切字符数。

这种技术好吗?我真的不知道还能做什么。

以下示例在 Visual Studio 2013 中运行良好,并根据需要打印出“hello”。

const char * m()
{
    char * c = (char *)malloc(6 * sizeof(char));
    c = "hello";
    return (const char *)c;
}    

int main(int argc, char * argv[])
{
    const char * d = m();
    std::cout << d; // use PCSTR
}

【问题讨论】:

  • 一次用两种不同的编程语言编写一个程序是个坏主意。选择一种语言。如果您的编译器是 Visual Studio,那么您绝对应该选择纯 C++,因为 VS 与标准 C 的一致性非常差。
  • 为什么是 C++ 标签?看起来像普通的 c。
  • 仅供参考,“sizeof(char)”根据定义 1.
  • @TNA std::cout 是 C++。

标签: c++ c malloc const-char const-pointer


【解决方案1】:

第二行“大错特错”:

char* c = (char*)malloc(6*sizeof(char));
// 'c' is set to point to a piece of allocated memory (typically located in the heap)
c = "hello";
// 'c' is set to point to a constant string (typically located in the code-section or in the data-section)

您将变量c 分配了两次,所以很明显,第一次分配没有意义。 这就像写作:

int i = 5;
i = 6;

最重要的是,您“丢失”了分配内存的地址,因此您以后将无法释放它。

您可以按如下方式更改此功能:

char* m()
{
    const char* s = "hello";
    char* c = (char*)malloc(strlen(s)+1);
    strcpy(c,s);
    return c;
}

请记住,拨打char* p = m() 的人也必须稍后再拨打free(p)...

【讨论】:

  • 只是为了好玩^^:sizeof("hello") strlen("hello") + 1(避免strlen 调用和需要s 变量)=> 做malloc(sizeof("hello"))strcpy(c, "hello")
  • @Zuzel:OP 显然误解了语言中的一些基本概念(至少在发布问题时)。我想尽可能地坚持原始代码,以便查明错误并避免进一步的混乱。谢谢。
  • 是的,我同意,我的意图不是要求回答编辑 :) 我通常喜欢对这些小“技巧”​​(语言细节)感到惊讶,评论注定如此好奇读者;)
【解决方案2】:

一种方法是返回一个本地静态指针

const char * m()
{
    static char * c = NULL;
    free(c);

    c = malloc(6 * sizeof(char));
    strcpy(c, "hello"); /* or fill in c by any other way */
    return c;
}    

这样,每当下次调用m() 时,c 仍然指向之前分配的内存块。您可以按需重新分配内存,填写新内容并返回地址。

【讨论】:

    【解决方案3】:

    没有。这不行。当你这样做时

    c = "hello";  
    

    malloc分配的内存丢失了。
    你可以这样做

    const char * m()
    {
        char * c = (char *)malloc(6 * sizeof(char));
        fgets(c, 6, stdin);
        return (const char *)c;
    }    
    

    【讨论】:

    • 如果我将该行更改为:c = strcpy(c, "hello");
    • @sailingonward:不,c = "string"只读字符串的地址分配给指针变量。之前分配给 c 的内存地址丢失了
    猜你喜欢
    • 2020-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-16
    • 1970-01-01
    • 2022-11-10
    • 2013-11-20
    • 2021-04-02
    相关资源
    最近更新 更多