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

pap*_*uck 4 c c++ malloc const-char const-pointer

我正在编写一个从.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
}
Run Code Online (Sandbox Code Playgroud)

bar*_*nos 7

第二行是"可怕的"错误:

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)
Run Code Online (Sandbox Code Playgroud)

你要c两次赋值变量,所以很明显,第一个赋值没有意义.这就像写作:

int i = 5;
i = 6;
Run Code Online (Sandbox Code Playgroud)

最重要的是,您"丢失"了已分配内存的地址,因此您将无法在以后发布它.

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

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

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