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

C++ 使用malloc()为const char字符串动态分配内存,c++,c,malloc,const-char,const-pointer,C++,C,Malloc,Const Char,Const Pointer,我正在编写一个程序,从.ini文件中读取一个值,然后将该值传递到一个接受PCSTR(即const char*)的函数中。函数是getaddrinfo() 因此,我想编写PCSTR ReadFromIni()。为了返回常量字符串,我计划使用malloc()分配内存,并将内存转换为常量字符串。我将能够获得从.ini文件中读取的确切字符数 这个技巧行吗?我真的不知道还能做什么 以下示例在Visual Studio 2013中运行良好,并根据需要打印“hello” const char * m() {

我正在编写一个程序,从.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
}
const char*m()
{
char*c=(char*)malloc(6*sizeof(char));
c=“你好”;
返回(常量字符*)c;
}    
int main(int argc,char*argv[])
{
常量char*d=m();

std::coutNO。这不好。当你这样做的时候

c = "hello";  
malloc
分配的内存丢失。
你可以随心所欲

const char * m()
{
    char * c = (char *)malloc(6 * sizeof(char));
    fgets(c, 6, stdin);
    return (const char *)c;
}    
一种方法是返回本地静态指针


这样,每当下次调用
m()
时,
c
仍然指向先前分配的内存块。您可以根据需要重新分配内存,填写新内容,然后返回地址。

第二行“严重”错误:

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)
char* m()
{
    const char* s = "hello";
    char* c = (char*)malloc(strlen(s)+1);
    strcpy(c,s);
    return c;
}
您将变量
c
赋值两次,因此很明显,第一次赋值没有意义。 就像在写:

int i = 5;
i = 6;
最重要的是,您“丢失”了已分配内存的地址,因此以后无法释放它

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

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)
char* m()
{
    const char* s = "hello";
    char* c = (char*)malloc(strlen(s)+1);
    strcpy(c,s);
    return c;
}

请记住,无论谁调用
char*p=m()
,都必须在稍后的某个时间调用
free(p)

如果我将该行更改为:
c=strcpy(c,“hello”);
@sailingonward:No,
c=“string”将只读字符串的地址分配给指针变量。以前分配给C的内存地址是LoStIt是一个坏主意,同时用两种不同的编程语言编写一个程序。选择一种语言。如果编译器是VisualStudio,那么您应该绝对满足纯C++,因为VS具有可怕的一致性。C++ C++标签为什么看起来像纯C?只是定义为“sieOf(char)”,定义为1。@仅为好玩^ ^:<代码> sieof(“hello”)<代码>斯特伦(“hello”)+ 1 < /C>(避免代码> StLLN < /CUD>调用和需要<代码> S/<代码>变量)= Do> <代码> Malc(siHeof(“Hello”))< <代码> >代码> StrucPy(C,Hello)
@Zuzel:OP显然误解了语言中的一些基本概念(至少在问题发布时是这样)。我希望尽可能地坚持原始代码,以查明错误并避免进一步混淆。谢谢。是的,我同意,我的意图不是要求编辑答案:)我通常喜欢对这些小“把戏”(语言细节)感到惊讶,这条评论注定是给好奇的读者的;)