简体   繁体   English

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

[英]Dynamically allocating memory for const char string using malloc()

I am writing a program that reads a value from an .ini file, then passes the value into a function that accepts a PCSTR (ie const char *). 我正在编写一个从.ini文件中读取值的程序,然后将该值传递给接受PCSTR的函数(即const char *)。 The function is getaddrinfo() . 该函数是getaddrinfo()

So, I want to write PCSTR ReadFromIni() . 所以,我想写PCSTR ReadFromIni() To return a constant string, I plan on allocating memory using malloc() and casting the memory to a constant string. 要返回一个常量字符串,我计划使用malloc()分配内存并将内存转换为常量字符串。 I will be able to get the exact number of characters that were read from the .ini file. 我将能够获得从.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
}

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 c twice, so obviously, the first assignment has no meaning. 你将变量c分配两次,所以很明显,第一个赋值没有意义。 It's like writing: 这就像写作:

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) ...

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, c still points to the memory block allocated earlier. 这样,每当下一次调用m()c仍然指向先前分配的内存块。 You could reallocate the memory on demand, fill in new content, and return the address. 您可以按需重新分配内存,填写新内容并返回地址。

NO. 没有。 This is not OK. 这不行。 When you do 当你这样做

c = "hello";  

the memory allocated by malloc lost. malloc分配的malloc丢失了。
You can do as 你可以这样做

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM