strcat and strncat in C: solved exercise
strcat and strncat in C: solved exercise
If you searched for a solved strcat and strncat exercise in C, here are the essential patterns: concatenating two strings with strcat, safe bounded concatenation with strncat, and building strings step by step without buffer overflow.
strncat(dst, src, n) appends at most n characters from src to the end of dst and always null-terminates. The n parameter is the number of characters to copy from the source, not the total size of the destination buffer.
Problem statement
- Build the string
"Hello, world!"by concatenating parts withstrcat. - Repeat using
strncatwith a character limit. - Show how to correctly calculate remaining space before calling
strncat.
C solution
Expected output
Common mistakes
- Passing the total buffer size as
ntostrncat:nis the number of characters to copy from the source, not the available space. You must computesizeof(dst) - strlen(dst) - 1to get the real remaining capacity. - Not reserving enough space in
dstbeforestrcat: ifdstis too small, a buffer overflow occurs. - Confusing
strncatwithstrncpy:strncatalways appends\0;strncpydoes not ifn < strlen(src). - Chaining many
strcatcalls instead of usingsnprintf:snprintfis cleaner, safer, and more efficient for building composite strings.
Practical use
strncat is used to incrementally build strings with fixed-size buffers: filesystem paths, protocol messages, or HTML fragments. In new code, snprintf is preferred for building the entire string at once.
Recommended next exercise
- sprintf and snprintf in C: solved exercise
- strcpy and strncpy in C: solved exercise
- strtok in C: solved exercise
- All C exercises
Guided practice and full book
If you want a complete path with progressive difficulty:
FAQ
What is the exact difference between strcat and strncat?
strcat(dst, src) copies all characters from src up to and including its \0 onto the end of dst, with no limit. strncat(dst, src, n) copies at most n characters from src and always appends \0. The difference is safety: strncat lets you control how much is appended.
Why is strncat’s n parameter not the destination buffer size?
By historical C design. n tells how many characters to take from the source. To compute the real available space in dst, calculate sizeof(dst) - strlen(dst) - 1 and pass that as n.
When is snprintf better than strncat?
Almost always. snprintf(buf, sizeof(buf), "%s%s", part1, part2) is clearer, safer, and more efficient than multiple strncat calls. Prefer strncat only when appending a fragment to an existing string and the overhead of snprintf is unacceptable.