Review a generated label-copy helper

from C preprocessor
C23 (GCC 13.3.0) advanced 7 min 4 issues to find

Review this generated C23 code before it enters a portable library.

Copy a label into caller storage only when it fits, terminate it, preserve the destination on failure, and compile tracing only when FEATURE_TRACE is 1.

C
#include <stddef.h>
#include <stdio.h>
#include <string.h>

#define FEATURE_TRACE 0
#ifdef FEATURE_TRACE
#define TRACE(format, ...) printf(format, ##__VA_ARGS__)
#else
#define TRACE(format, ...) ((void)0)
#endif

#define COPY_LABEL(dst, src, count) do { \
    memcpy((dst), (src), (count)); \
    (dst)[(count)] = '\0'; \
} while (0)

size_t store_label(char *dst, size_t capacity,
                   const char *src, size_t length) {
    if (length > capacity) return 0;
    COPY_LABEL(dst, src, length);
    TRACE("stored %zu\n", length);
    return length;
}

generated code is illustrative, not from any one model

Open in playground
Report an error