0

My code :

#include <stdio.h>
#include <cs50.h>

int get_positive_int(string prompt);

int main(void)
{
    int i = get_positive_int("Positive interegr: ");
    printf("%i\n", i);
}

int get_positive_int(string prompt)
{
    int n;
    do
    {
        n = get_int(prompt);
    }
    while (n < 1);
    return n;
}

The err Clang gives me for this code:

clang -fsanitize=signed-integer-overflow -fsanitize=undefined -ggdb3 -O0 -std=c11 -Wall -Werror -Wextra -Wno-sign-compare -Wno-unused-parameter -Wno-unused-variable -Wshadow    positive.c  -lcrypt -lcs50 -lm -o positive
positive.c:17:21: error: format string is not a string literal (potentially insecure) [-Werror,-Wformat-security]
        n = get_int(prompt);
                    ^~~~~~
positive.c:17:21: note: treat the string as an argument to avoid this
        n = get_int(prompt);
                    ^
                    "%s", 

I am unable to figure out my syntax mistakes. Can someone help me?

1 Answer 1

0

get_int passes its arguments to printf.

The first argument to printf is a format string, a template for what to print.

You shouldn't let anyone control the format string, as that could be abused to leak or overwrite other variables. That's why the compiler does not like it, and wants you to use a string literal for the format string. With get_int("%s", prompt), you use a string literal, and the prompt is taken as a plain string, not interpreting any % characters inside.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .