how can this code compile w/o problem ?

Hi all,
Please see the pasted code below,my question is when the compiler reaches variable buf, how much space can it determine to allocate for buf, because vsnprintf(NULL, 0, fmt, args1) is a run-time result? I think it should be a compilation error but I have tested and it runs pretty well.

Please help, thanks in advance !

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <stdio.h>
#include <stdarg.h>
#include <time.h>
 
void debug_log(const char *fmt, ...)
{
    struct timespec ts;
    timespec_get(&ts, TIME_UTC);
    char time_buf[100];
    size_t rc = strftime(time_buf, sizeof time_buf, "%D %T", gmtime(&ts.tv_sec));
    snprintf(time_buf + rc, sizeof time_buf - rc, ".%06ld UTC", ts.tv_nsec / 1000);
 
    va_list args1;
    va_start(args1, fmt);
    va_list args2;
    va_copy(args2, args1);
    char buf[1+vsnprintf(NULL, 0, fmt, args1)];
    va_end(args1);
    vsnprintf(buf, sizeof buf, fmt, args2);
    va_end(args2);
 
    printf("%s [debug]: %s\n", time_buf, buf);
}
 
int main(void)
{
    debug_log("Logging, %d, %d, %d", 1, 2, 3);
}
This is valid C code. Variable Length Arrays were introduced in C in C99.
This is invalid C++ code, however some compilers (GCC) provide support for this C feature in C++ as extension.
Last edited on
thanks a lot for your help !
Topic archived. No new replies allowed.