[英]Dynamically allocating memory for const char string using malloc()
我正在編寫一個從.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)
...
一種方法是返回本地靜態指針 。
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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.