使用malloc()为const char字符串动态分配内存, [英] Dynamically allocating memory for const char string using malloc()

查看:207
本文介绍了使用malloc()为const char字符串动态分配内存,的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



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



这种技术好吗?



以下示例在Visual Studio 2013中运行良好,并根据需要打印hello。

  const char * m()
{
char * c =(char *)malloc * 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 sizeof(char)); 
//'c'设置为指向一块分配的内存(通常位于堆中)
c =hello;
//'c'设置为指向一个常量字符串(通常位于代码段或数据部分)

你分配变量 c 两次,所以很明显,第一个赋值没有意义。
它就像写:

  int i = 5; 
i = 6;

最重要的是,你会丢失分配的内存的地址,所以你不会


$ b

p $ p> char * m()
{
const char * s =hello;
char * c =(char *)malloc(strlen(s)+1);
strcpy(c,s);
return c;请记住,任何调用 char * p =



$ b < m()
也必须在以后调用 free(p) ...


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

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.

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.

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

这篇关于使用malloc()为const char字符串动态分配内存,的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆