c/c++语言开发共享使用malloc()为const char字符串动态分配内存

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

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

     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; 

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

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

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

    请记住,无论谁调用char* p = m() ,都必须稍后调用free(p)

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

     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仍然指向先前分配的内存块。 您可以按需重新分配内存,填写新内容并返回地址。

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

     c = "hello"; 

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

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

      以上就是c/c++开发分享使用malloc()为const char字符串动态分配内存相关内容,想了解更多C/C++开发(异常处理)及C/C++游戏开发关注计算机技术网(www.ctvol.com)!)。

      本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

      ctvol管理联系方式QQ:251552304

      本文章地址:https://www.ctvol.com/c-cdevelopment/560011.html

      (0)
      上一篇 2021年1月27日
      下一篇 2021年1月27日

      精彩推荐