Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trouble Wrapping Printf in C Program

Tags:

c

printf

I'm trying to wrap printf in a C program (well, actually _snprintf but this example is simpler) and am having trouble getting the variable argument stuff to work. Here is my code:

#include <stdio.h>
#include <stdarg.h>

void works(void)
{
    printf("%d\n", 100);
}

void wrap_printf(const char *fmt, ...)
{
    va_list args;
    va_start(args, fmt);
    printf(fmt, args);
    va_end(args);
}

void broken(void)
{
    wrap_printf("%d\n", 100);
}

int main(void)
{
    works();
    broken();
    return 0;
}

Here is my output:

100
3668388

The args variable looks good after the call to va_start in my code, but as soon as I step into the C runtime code and they call va_start the value looks bad. Any thoughts as to what I might be doing wrong?

like image 313
user1421964 Avatar asked May 28 '12 15:05

user1421964


People also ask

How printf works in C?

The printf function (the name comes from “print formatted”) prints a string on the screen using a “format string” that includes the instructions to mix several strings and produce the final string to be printed on the screen.

Can you write printf in C?

In the C Programming Language, the printf function writes a formatted string to the stdout stream.

How many arguments must be sent to the printf() function?

In your first case, it takes 3 arguments. In the second case, it takes 4 arguments. printf is a variadic function. It takes a variable number of arguments.


2 Answers

va_start(args, fmt);
vprintf(fmt, args);
va_end(args);

You need to call vprintf instead of printf. The v*printf functions understand va_List arguments. I'm surprised you didn't get a warning.

like image 75
cnicutar Avatar answered Oct 27 '22 02:10

cnicutar


You're passing args which is a va_list, but printf() of course expects the arguments directly, it has no way of knowing that its second argument suddenly is a va_list.

You should be using vprintf(), the variable-argument version which does indeed expect a va_list and knows how to extract the values from it.

like image 22
unwind Avatar answered Oct 27 '22 01:10

unwind