Search code examples
cellipsisnrf52

Ellipsis issue with va_start() on nRF52840


I want to retreive my args from an ellipsis using va_start.

Here is my code :

char str[256];
void nrf_log_flash(bool is_to_save, char * log, ...){
    va_list args;
    va_start(args, log);
    int ret = vsprintf(str, log, args);
    if(is_to_save){
         sprintf(str, "%s : %s\n", nrf_cal_get_time_string(false), log);
         //my_nrf_log_add(str, strlen(str));
    }
    NRF_LOG_INFO("%s", log);
    NRF_LOG_INFO("%s", str);
    NRF_LOG_INFO("%d", ret);
    va_end(args);

}

And here is my calling :

nrf_log_flash(true, "button %d pressed, %u, %x, %c", 2, 3658, 0xca, 'a');

But my va_list is empty. What am I doing wrong ?


Solution

  • After the line

    int ret = vsprintf(str, log, args);
    

    your str variable contains the formatted string (e.g. str is "button 2 pressed, 3658, ca, a". however, you next sentence overwrite this data. as you call sprintf, and overwrite the data at str with the 'log' variable which is the format ("button %d pressed, %u, %x, %c")

    if(is_to_save){
         //THIS CODE OVERWRITE YOUR STR BUFFER
         sprintf(str, "%s : %s\n", nrf_cal_get_time_string(false), log);
         //my_nrf_log_add(str, strlen(str));
    }
    

    BTW, it is recommended to use snprint, and vsnprintf to avoid buffer overflow. as the format contains '%s', it may be printed with a large string which is larger than 256 bytes.