areify
areify

Reputation: 57

printf inside variadic function prints garbage

I am trying to create a customizable debug library so I can declare my debug function outside and set it to the library as a callback, so others libraries can call this debug functions without knowing how are defined those callbacks.

My debug.c file contains the following extracts:

// NOTE: type defined in .h as: typedef void(*debug_custom_callback_t)(const char *format, ...);
debug_custom_callback_t debug_custom_callback[DEBUG_NUM_CALLBACKS];


void debug_log_printf(uint8_t idx, const char *format, ...){

   va_list args;

    // callback exists
    if(debug_custom_callback[idx]){
        va_start(args, format);
        debug_custom_callback[idx](format, args);
        va_end(args);
    }
    
}

void debug_set_callback(uint8_t idx, debug_custom_callback_t callback){

   //callback assigning
   if(callback && idx < DEBUG_NUM_CALLBACKS)
      debug_custom_callback[idx] = callback;

}

This library has is own makefile so it can be compiled as a .a lib and is being linked with -l flag in the makefile of the main code.

Main code uses debug library as follows:

   ...
   
   //main code
   
   uint8_t test = 0xFF;
   
   debug_set_callback(0, main_printf);
   debug_log_printf(0, "Testing %d %d\n", test, 1); // prints: Testing -1095376668 -1225391600
   
   ...
   
   
   
   //Definition of main_printf
   void main_printf(const char *format, ...){
       va_list args;

       va_start(args, format);
       printf(format, args);
       va_end(args);
    }

But this is not working fine. The string is printed properly, but any value that I try to print is printed as garbage. As you can see, even the constants are being printed badly.

What am I missing?

Thank you in advance.

Upvotes: 1

Views: 154

Answers (1)

Andrejs Cainikovs
Andrejs Cainikovs

Reputation: 28474

Use vprintf instead.

void main_printf(const char *fmt, va_list args) {
    vprintf(fmt, args);
}

Upvotes: 1

Related Questions