Variable-Argument Functions Across Languages, with a Safe Logger
Data Structure DesignModel answerLast updated
Compare how two languages implement functions with a variable number of arguments, then design a type-checked key-value logger that avoids injection and needless allocation.
Many languages let a function accept a variable number of arguments, such as printf in C, *args in Python, ...T in Go and T... in Java.
Pick two languages (for example C/C++ and Python, or Go and Java) and explain the following for each.
- Mechanics. How does the caller pass the extra arguments, and how does the callee read them? Cover the calling convention (stack, registers, or a container object) and how the callee learns the count and types.
- Type safety. What does the compiler or runtime check? Contrast raw varargs with templates, generics or typed alternatives.
- Cost. What are the performance, stack and heap implications?
- Forwarding. How do you pass the variable arguments on to another function?
Then design and implement a type-safe logger that accepts a level, a message and key-value fields, and formats them into a single line efficiently. Discuss:
- format-string vulnerabilities,
- boxing and reflection overhead,
- overload or keyword ambiguity,
- log forging through unescaped values.
Also provide unit tests and state the time and space complexity of your formatting routine.
Hints
Hint 1
Start by listing the three questions every variadic design must answer: where the extra arguments live, how the callee knows their count and types, and whether anything checks them. Then compare one unchecked model with one checked model.
Hint 2
For the logger, treat the message as data and never as a format string. Validate keys and value types up front, and check the log level before doing any validation or formatting work.
Hint 3
Build the output by collecting parts in a list and joining once, and quote or escape values containing spaces, equals signs, quotes or newlines. For tests, cover an odd number of positional pairs, a field named like a parameter, bool versus int, and a disabled level.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Framing
A variadic function accepts a variable number of arguments. Every language answers three questions differently:
- Where do the extra arguments live: registers, the stack, or a heap container?
- How does the callee learn the count and types: a format string, a sentinel, a length field, or compile-time types?
- Who checks them: nobody, the compiler, or the runtime?
I will contrast C (unchecked) with Python (dynamic and container-based), with short notes on C++, Go and Java.
C: raw varargs
#include <stdarg.h>
int sum(int count, ...) {
va_list ap;
va_start(ap, count);
int s = 0;
for (int i = 0; i < count; i++) s += va_arg(ap, int);
va_end(ap);
return s;
}
- Convention. The caller pushes or places the arguments, and the callee has no idea how many there are. On x86-64 System V the first arguments arrive in registers. The prologue spills them to a register save area so
va_argcan walk them, and%alcarries the number of vector registers used. - Promotions.
floatbecomesdouble, andcharandshortbecomeint. Callingva_arg(ap, float)is undefined behavior. - Safety. None. Count and types follow a convention (format string, sentinel, count parameter), and a mismatch is undefined behavior. Mitigate with
__attribute__((format(printf,1,2)))and-Wformat. - Forwarding. You cannot forward
...directly. Accept it, build ava_list, and call av-variant such asvsnprintf. Useva_copyif you must traverse twice. - Security.
printf(user_input)lets an attacker read the stack with%xand write memory with%n. Always writeprintf("%s", user_input).
C++: variadic templates
template <class... Args>
void log(std::string_view msg, Args&&... args) {
sink(msg, std::forward<Args>(args)...);
}
- The parameter pack is expanded at compile time, and each distinct call shape produces its own instantiation.
- Types are fully checked, and
requiresclauses can constrain them. There is no boxing, and calls often inline completely. - The price is code bloat and longer compile times.
- Overload ranking: a non-template beats a template, a more specialized template beats a variadic one, and C-style
...ranks last.
Python: *args and **kwargs
- Extra positional arguments are packed into a tuple and keyword arguments into a dict, both heap-allocated on every call.
- The callee always knows the count and runtime types. This is safe but dynamic.
- Forwarding is
f(*args, **kwargs). - Static typing options are
*args: int,ParamSpecfor decorators andTypeVarTuplefor heterogeneous packs. - Ambiguity arises when a keyword collides with a named parameter, for example
log("x", msg=...). Positional-only parameters (/) fix this.
Go and Java in brief
- Go.
...Tyields a slice, forwarded asf(xs...)....anyboxes each value into an interface, which often escapes to the heap.log/slogavoids this with typed attribute constructors. - Java.
T...yields an array allocated per call, andObject...autoboxes primitives. Varargs are considered only in the third phase of overload resolution, sof(null)is ambiguous between a null array and a single null element. Generic varargs cause heap-pollution warnings, which@SafeVarargssuppresses.
Designing the logger
Design decisions follow directly from the pitfalls:
- The message is data, never a format string. Fields are structured, so injection through the message is impossible.
- Validate eagerly. Keys must be non-empty strings with no whitespace,
=or quotes. Values must be scalars (str,int,float,bool,None). Anything else raisesTypeErrorrather than silently callingrepr, which may be slow or leak secrets. - Two call styles.
**fieldsis idiomatic and checkable. Alternating*pairssupports dynamic keys, asslogdoes. An odd number of pairs is an error. - Positional-only
levelandmsg, so a field namedmsgcannot collide. - Check the level first, so disabled calls skip validation and formatting entirely.
- Join once. Collect parts in a list and call
"".join. Repeated+=would be quadratic in the worst case. - Quote and escape values containing whitespace,
=, quotes, backslashes or newlines, which prevents log forging.
from typing import Callable, Optional, Union
Scalar = Union[str, int, float, bool, None]
DEBUG, INFO, WARN, ERROR = 10, 20, 30, 40
_NAMES = {DEBUG: "DEBUG", INFO: "INFO", WARN: "WARN", ERROR: "ERROR"}
_SPECIAL = set(' ="\n\r\t\\')
def _fmt_value(v: Scalar) -> str:
if v is None:
return "null"
if isinstance(v, bool): # before int: bool subclasses int
return "true" if v else "false"
if isinstance(v, (int, float)):
return repr(v)
if isinstance(v, str):
if v and not any(c in _SPECIAL for c in v):
return v
esc = (v.replace("\\", "\\\\").replace('"', '\\"')
.replace("\n", "\\n").replace("\r", "\\r")
.replace("\t", "\\t"))
return f'"{esc}"'
raise TypeError(f"unsupported value type: {type(v).__name__}")
def _check_key(k: object) -> str:
if not isinstance(k, str):
raise TypeError("field key must be str")
if not k or any(c in _SPECIAL for c in k):
raise ValueError(f"invalid field key: {k!r}")
return k
class Logger:
def __init__(self, sink: Optional[Callable[[str], None]] = None,
level: int = INFO) -> None:
self._sink = sink or print
self.level = level
def log(self, level: int, msg: str, /, *pairs: Scalar,
**fields: Scalar) -> None:
if level < self.level:
return
if not isinstance(msg, str):
raise TypeError("msg must be str")
if len(pairs) % 2:
raise ValueError("pairs must alternate key, value")
parts = [f"level={_NAMES.get(level, str(level))}",
f"msg={_fmt_value(msg)}"]
for i in range(0, len(pairs), 2):
parts.append(f"{_check_key(pairs[i])}={_fmt_value(pairs[i+1])}")
for k, v in fields.items():
parts.append(f"{_check_key(k)}={_fmt_value(v)}")
self._sink(" ".join(parts))
Tests to include
- A disabled level emits nothing and does no validation.
- An odd number of pairs raises
ValueError. - A key containing a space or
=raisesValueError, and a non-string key raisesTypeError. - A list or object value raises
TypeError. Truerenders astrue, not1.- A value containing a newline is escaped, so exactly one line is emitted.
- A message containing
%sor{}is output verbatim. - A field named
msgpassed through**fieldsdoes not collide with the positional parameter.
Complexity
With n fields and total character length L, formatting is O(n + L) time, since each character is scanned and escaped a constant number of times and the final join is linear. Space is O(n + L) for the parts list and output string. Disabled calls are O(1) after the level check, apart from the unavoidable argument packing by the language.
Common mistakes
- Passing user text as the format string.
- Using
isinstance(v, int)before checkingbool. - Calling
str()orrepr()on arbitrary objects, which is slow and can leak data. - Formatting before checking the level.
- Not escaping newlines, which allows forged log lines.
- Claiming Python varargs are free when each call allocates a tuple and a dict.