當我嘗試運行此代碼時:
char *s;
s = (char *) malloc (15);
s = "hello world";
free(s);
使用gcc ts.c -ansi -Wall結果是:
free(): invalid pointer
Aborted (core dumped)
警告是:
‘free’ called on a pointer to an unallocated object
我不明白為什么 char 指標與其他指標不同。
uj5u.com熱心網友回復:
此代碼段
char *s;
s = (char *) malloc (15);
s = "hello world";
產生記憶體泄漏。
起初,記憶體是動態分配的,它的地址被分配給指標 s
s = (char *) malloc (15);
然后s用字串文字的第一個字符的地址重新分配指標
s = "hello world";
其實上面的陳述句等價于
s = &"hello world"[0];
字串文字具有靜態存盤持續時間。因此,您可能不會將該函式free應用于字串文字。
而不是這個任務
s = "hello world";
您需要使用strcpy標頭中宣告的標準字串函式<string.h>
#include <string.h>
//...
strcpy( s, "hello world" );
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/412250.html
標籤:
上一篇:警告:從不兼容的指標型別回傳[-Wincompatible-pointer-types]|
下一篇:嘗試列印出鏈表時出現分段錯誤
