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

 mobiledu2502887493 发布于 2023-01-29 11:19

我正在编写一个从.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
}

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

你要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)在稍后的时间打电话......

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)在稍后的时间打电话......

    2023-01-29 11:21 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有