preprocessor-toolchain · beginner · ~15 min

Source Location Diagnostic Logger

Format diagnostic source traces using preprocessor location symbols with strict truncation detection.

Challenge

Standard C provides predefined macros (__FILE__, __LINE__, and __func__) that the preprocessor and compiler populate at compile time. Diagnostic frameworks use these to embed exact source locations into crash logs and debug traces.

Your Task

Implement:

int format_source_location(char *buf, size_t cap, const char *file, int line, const char *func, const char *msg);

Rules

  1. If buf == NULL, file == NULL, func == NULL, msg == NULL, or cap == 0, return -1.
  2. Format the string into buf using snprintf with the exact pattern: "[file:line in func()] msg"
  3. If the formatted output (including terminating NUL) does not fit completely within cap, return -1.
  4. On success, return the number of characters written (excluding NUL).

Example

char out[64];
format_source_location(out, sizeof(out), "main.c", 42, "init", "ready");
// out becomes: "[main.c:42 in init()] ready"

Input format

buf: output char buffer; cap: buffer capacity; file: filename; line: line number; func: function name; msg: log message.

Output format

Returns characters written on success, or -1 on truncation/invalid arguments.

Constraints

Must use snprintf safely to detect truncation without overflowing buffer.

Starter code

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

/* Format "[file:line in func()] msg" into buf up to cap. Return written count or -1 on truncation/error. */
int format_source_location(char *buf, size_t cap, const char *file, int line, const char *func, const char *msg) {
    (void)buf; (void)cap; (void)file; (void)line; (void)func; (void)msg;
    return -1;
}

Common mistakes

Ignoring snprintf return value >= cap indicating truncation; forgetting NUL byte accounting.

Edge cases to handle

Buffer too small by 1 byte returns -1; cap == 0 returns -1; NULL pointers return -1.

Background lessons

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.