user1559897
user1559897

Reputation: 1484

Why does not this file compile in gcc? It works fine in VS

g++ would nt even compile it. Where was I wrong? These are the error message:

gcc sign.c sign.c: In function âmainâ: sign.c:35:2: warning: format not a string literal and no format arguments [-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");
    }
}

Upvotes: 0

Views: 112

Answers (3)

sehe
sehe

Reputation: 392931

You should not use printf with an unknown format string:

printf(words);

Try

printf("%s", words);

In this case,

printf("%s\n", words);
puts(words); // includes \n

would be nice

Upvotes: 2

Vlad
Vlad

Reputation: 35584

The warning says basically that you have to write

printf("%s", words);

instead of just

printf(words);

Indeed, using it could be a potential bug in your program, and even a security breach, e.g. if words is controlled by the user (which is exactly the case for your program) and may therefore contain %n etc. In your case, words will be treated as a format specifier.

Upvotes: 3

Greg Hewgill
Greg Hewgill

Reputation: 993055

First, that's just a warning message, which means the compiler detected something probably wrong but compiled your code anyway. Not all compilers give the same warnings, as you've noticed.

The problem is this line (and all the other lines like it):

printf(words);

When using printf, you must use a format string, something like this:

printf("%s", words);

Otherwise, if the things you're printing (words) happens to have any % characters in it, then printf() will treat those as formatting specifiers and try to read arguments that you haven't supplied.

If you just want to print a string by itself, then puts can be useful:

puts(words);

This prints words followed by a newline.

Upvotes: 11

Related Questions