1
#include <stdio.h>

int main(void) {
    int b= 37;
    char a=10, str[32] = "deva%x %x", buf[32];
    snprintf(buf, sizeof(buf), str);
    printf("%s", buf);
    printf("\n %p", &b);
    return 0;
}

Ouput: deva80482b9 40020930 0xbfb80aac

Wondering how printf is working here & what is the value it's printing. Does it have any significance ??

3 Answers 3

2

This is undefined behavior, since the arguments passed to snprintf() don't match the format string.

No further analysis of what happens in general is very interesting, since what happens is undefined and might change from one compilation of the program to another.

The most likely explanation is that printf() proceeds as if the arguments where there, reading data from foo-knows-where.

Sign up to request clarification or add additional context in comments.

6 Comments

I always assumed the first argument in the printf statement is the one that should contain format specifiers, is my understanding is not correct.
Sure, but this is a call to snprintf(), which is not the same function as printf(). This formats to a size-limited string buffer (which is what the prefix sn typically means).
Yup, got confused. Wondering will it try to read data in stack ??
@Deva That is undefined. Nobody knows, except maybe the people who implemented your particular combination of compiler and standard library. You can of course disassemble and/or debug the program to find out what it does, but that doesn't tell you much in general.
@Deva You can make a pretty good guess as to where it reads the arguments from if you know the calling conventions. Most likely they come from the fourth and fifth registers or from the stack somewhere below the return address.
|
0

In your statement

 snprintf(buf, sizeof(buf), str);

the format string contains conversion specifiers (%x), but corresponding arguments are missing. So, this invokes undefined behavior.

Quoting C11, chapter §7.21.6.1/p2,

[....] If there are insufficient arguments for the format, the behavior is undefined. [...]

You need to write

snprintf(buf, sizeof(buf), str, <list of arguments matching the conversion specifier>);

Check the man page for more details.

Comments

0

undefined behavior, as because you have passed wong arguments snprintf() don't match the format string.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.