C++ 使用 malloc() 为 const char 字符串动态分配内存

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21579819/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 23:42:47  来源:igfitidea点击:

Dynamically allocating memory for const char string using malloc()

c++cmallocconst-charconst-pointer

提问by paperduck

I am writing a program that reads a value from an .ini file, then passes the value into a function that accepts a PCSTR (i.e. const char *). The function is getaddrinfo().

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

So, I want to write PCSTR ReadFromIni(). To return a constant string, I plan on allocating memory using malloc()and casting the memory to a constant string. I will be able to get the exact number of characters that were read from the .ini file.

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

Is that technique okay?I don't really know what else to do.

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

The following example runs fine in Visual Studio 2013, and prints out "hello" as desired.

以下示例在 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
}

回答by barak manos

The second line is "horribly" wrong:

第二行是“可怕的”错误:

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)

You are assigning variable ctwice, so obviously, the first assignment has no meaning. It's like writing:

您正在分配变量c两次,因此显然,第一次分配没有意义。这就像写:

int i = 5;
i = 6;

On top of that, you "lose" the address of the allocated memory, so you will not be able to release it later.

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

You can change this function as follows:

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

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

Keep in mind that whoever calls char* p = m(), will also have to call free(p)at some later point...

请记住,无论谁打电话char* p = m(),也必须free(p)在稍后的某个时间打电话......

回答by timrau

One way is to return a local static pointer.

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

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

This way, whenever the next time m()is called, cstill points to the memory block allocated earlier. You could reallocate the memory on demand, fill in new content, and return the address.

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

回答by haccks

NO. This is not OK. When you do

不。这不行。当你做

c = "hello";  

the memory allocated by malloclost.
You can do as

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

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