Summary - Advanced strings
- C course
- Intermediate
- Lesson 23/116
- 5 min
Combine dynamic strings, conversion and safety to write a string buffer.
Designing a string buffer
In this summary you'll combine malloc, strncpy and strncat to write a dynamic string buffer. The buffer accumulates strings safely.
First you allocate a large enough block with malloc. Then you copy the first string safely with strncpy; guaranteeing null termination. Then you append the second string with bounded strncat. This pattern is standard for user input and network data; it prevents overflow and leaks. When done, you free with free.
Practice Write a string buffer
Allocate a twenty-byte buffer with char *buf = malloc(20);. Copy the first string with strncpy(buf, "Merhaba", 19);. Null-terminate with buf[19] = '\0';. Append the second string with strncat(buf, " dünya", 19 - strlen(buf));. Print with printf("%s\n", buf);. Free with free(buf);. Include <stdlib.h> and <string.h>.
Starter code
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// Allocate 20 bytes with malloc
// Copy "Merhaba" with strncpy, null-terminate
// Append " dünya" with strncat, print and free
int main(void) {
return 0;
}Sample solution
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
char *buf = malloc(20);
strncpy(buf, "Merhaba", 19);
buf[19] = '\0';
strncat(buf, " dünya", 19 - strlen(buf));
printf("%s\n", buf);
free(buf);
return 0;
}Expected output
Merhaba dünya
Summary
In this group you learned advanced string handling techniques. For dynamic strings malloc, for concatenation strcat and sprintf, for search strstr and strchr, for conversion atoi, atof and strtol, for safety strncpy and strncat.
You combined them to write a safe string buffer. You allocated with malloc, copied safely with strncpy, appended with bounded strncat and freed with free. This pattern is the foundation of real-world text processing applications.
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the buffer steps
| Term | Meaning |
|---|---|
malloc |
Allocate |
strncpy |
Copy first string |
strncat |
Append second string |
free |
Release buffer |
2 Why is strncpy preferred in a string buffer?
- Because it checks the bound Correct answer
- Because it's faster
- Because it uses less memory
- Because it adds null automatically
Explanation: strncpy checks the bound; that's why it's preferred in safe buffers.