![](/img/trans.png)
[英]Why the below code does not compile with gcc but compiles fine with clang
[英]Why does not this file compile in gcc? It works fine in VS
g ++甚至不會編譯它。 我哪里錯了? 這些是錯誤消息:
gcc sign.c sign.c:在函數“ main”中:sign.c:35:2:警告:格式不是字符串文字,並且沒有格式參數[-Wformat-security]
================================================== ================================
#include "stdio.h"
int string_length(char str[]);
void string_sort(char s[]);
void string_sort(char s[])
{
char tmpt;
int i, j, len;
len=string_length(s);
for(i=0; i<len-1; i++){
for (j=i+1; j<len; j++){
if (s[i] > s[j]){
tmpt=s[i];
s[i]=s[j];
s[j]=tmpt;
}
}
}
}
int string_length(char str[]){
int i;
for(i=0; i<80; i++){
if(str[i]=='\0'){
return(i);
}
}
}
int main(){
char words[80];
scanf("%s", words);
printf(words);
string_sort(words);
printf(" ");
printf(words);
printf("\n");
while ( words != " "){
scanf("%s", words);
printf(words);
string_sort(words);
printf(" ");
printf(words);
printf("\n");
}
}
首先,這只是一個警告消息,這意味着編譯器檢測到可能是錯誤的東西,但是仍然編譯了您的代碼。 正如您所注意到的,並非所有編譯器都給出相同的警告。
問題是此行(以及所有其他類似的行):
printf(words);
使用printf
, 必須使用格式字符串,如下所示:
printf("%s", words);
否則,如果您要打印的內容( words
)恰好包含任何%
字符,則printf()
會將其視為格式說明符,並嘗試讀取您未提供的參數。
如果只想單獨打印一個字符串,則puts
可能會有用:
puts(words);
這將打印words
后跟換行符。
警告基本上說你必須寫
printf("%s", words);
而不只是
printf(words);
確實,使用它可能是程序中的潛在錯誤,甚至是安全漏洞,例如,如果words
是由用戶控制的(這正是程序的情況),因此可能包含%n
等。在您的情況下, words
將被視為格式說明符。
您不應將printf與未知的格式字符串一起使用:
printf(words);
嘗試
printf("%s", words);
在這種情況下,
printf("%s\n", words);
puts(words); // includes \n
會好的
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.