我正在编写一个程序,该程序从 .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;
最重要的是,您“丢失”了分配的内存的地址,因此以后将无法释放它。
您可以按如下方式更改此功能:
char* m()
{
const char* s = "hello";
char* c = (char*)malloc(strlen(s)+1);
strcpy(c,s);
return c;
}
请记住,无论谁打电话char* p = m()
,还必须致电free(p)
在稍后的某个时刻...
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)