Comment

Comment by TazeTSchnitzel

My favourite C string function is snprintf:

• It takes a buffer size and truncates the output to the buffer size if it's too large.

• The buffer size includes the null terminator, so the simplest pattern of snprintf(buf, sizeof(buf), …) is correct.

• It always null-terminates the output for you, even if truncated.

• By providing NULL as the buffer argument, it will tell you the buffer size you need if you want to dynamically allocate.

And of course, it can safely copy strings:

  snprintf(dst_buf, sizeof(dst_buf), "%s", src_str);
Including non-null-terminated ones:

  snprintf(dst_buf, sizeof(dst_buf), "%.*s", (int)src_str_len, src_str_data);
And it's standard and portable, unlike e.g. strlcpy. It's one of the best C99 additions.

Discussion

Live from the official Hacker News API

A modern reader for Hacker News · SvelteKit + Skeleton