每當我在用 C 編碼時嘗試使用 sprintf() 時,我都會收到一條警告說:
“警告:'%s' 指令將最多 49 個位元組寫入大小為 39 的區域 [-Wformat-overflow=]”
它還產生了一張紙條,上面寫著:
"注意:'sprintf' 輸出 13 到 62 個位元組到大小為 50 62 的目標 | sprintf(msg,"fopen-ing "%s"",data_file);"
下面我給出了我的代碼的一部分,主要是我收到這個警告的地方。
char data_file[50]; // Global
void initialize_from_data_file()
{
FILE *fpS;
if((fpS = fopen(data_file,"r")) == NULL)
{
char msg[50];
sprintf(msg,"fopen-ing \"%s\"",data_file);
perror(msg);
exit(1);
}
...
}
由于我剛剛使用這種語言,因此無法理解如何洗掉此警告。
uj5u.com熱心網友回復:
它警告您目標緩沖區sprintf可能不夠大,無法容納您想要放入其中的字串。如果data_file長度超過 40 個字符,sprintf則將寫入陣列末尾msg。
制作msg足夠大以容納將要放入其中的字串:
char msg[70];
然而,還有另一個問題。由于您在 callsprintf之前呼叫perror,后者將報告呼叫的錯誤狀態sprintf,而不是fopen呼叫。
所以sprintf在這種情況下根本不要使用并使用strerror來獲取錯誤字串:
fprintf(stderr,"fopen-ing \"%s\": %s",data_file,strerror(errno));
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/331906.html
