使用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; }