Dynamic String Builder
Part of the Object Oriented Programming section of Coddy's C journey — lesson 59 of 61.
Challenge
EasyLet's build a StringBuilder — a dynamic string container that grows automatically as you append text. This is a practical utility that combines dynamic memory management with the OOP patterns you've mastered throughout this course.
You'll organize your code across three files:
stringbuilder.h: Declare theStringBuilderstruct with three members: achar*buffer, asize_tfor the current length, and asize_tfor the total capacity. Declare function prototypes for creating a StringBuilder, appending text to it, retrieving the final string, and freeing the memory. Include guards are essential.stringbuilder.c: Implement your StringBuilder system:create_stringbuilder— allocates a StringBuilder on the heap, initializes the buffer with an initial capacity of 16 bytes, sets length to 0, and ensures the buffer starts as an empty string (null-terminated)append— takes a StringBuilder pointer and a string to append. Calculate the new required length. If it exceeds capacity, double the capacity (repeatedly if needed) and usereallocto grow the buffer. Then concatenate the new text usingstrcatget_string— returns a pointer to the internal buffer (read-only access)free_stringbuilder— frees the buffer first, then the StringBuilder struct itself
main.c: Read an integer indicating how many strings to append. Then read each string usingfgetsand append it to your StringBuilder. After all strings are added, print the complete assembled string usingget_string. Finally, free the StringBuilder.
Two key functions used in this challenge:
realloc(ptr, new_size)— resizes a previously allocated block of memory. It takes a pointer to the existing block and the new desired size in bytes, and returns a pointer to the (possibly moved) resized block. Use it inappendwhen the buffer needs to grow:sb->buffer = (char*)realloc(sb->buffer, sb->capacity);fgets(buffer, size, stream)— reads a line of text from an input stream into a character array, stopping at a newline or whensize - 1characters have been read. It keeps the newline character in the buffer, so you'll need to strip it manually. Use it inmain.cto read each input string:fgets(line, sizeof(line), stdin);
To strip the trailing newline: check if the last character is'\n'and replace it with'\0'.
Your program will receive:
- The number of strings to append
- Each string on a separate line
Example output when inputs are 3, then Hello, , World:
Hello WorldExample output when inputs are 4, then C, is, a, great language!:
C is a great language!Example output when inputs are 1, then SingleString:
SingleStringRemember to update the length field after each append operation. When checking if reallocation is needed, account for the null terminator — the buffer needs space for length + new_text_length + 1 bytes. Use strlen from <string.h> to measure string lengths. Also call getchar() after scanf in main.c to consume the leftover newline before reading strings with fgets.
Try it yourself
#include <stdio.h>
#include <stdlib.h>
#include "stringbuilder.h"
int main() {
int n;
scanf("%d", &n);
getchar(); // consume newline after number
// TODO: Create a StringBuilder using create_stringbuilder()
// TODO: Read n strings and append each to the StringBuilder
// Hint: Use fgets or similar to read each line
// Remember to handle the newline character from fgets if you use it
// TODO: Print the complete assembled string using get_string()
// TODO: Free the StringBuilder using free_stringbuilder()
return 0;
}
All lessons in Object Oriented Programming
1Modular Programming Basics
Header FilesInclude GuardsSource FilesStatic FunctionsRecap: Modular Calculator4Encapsulation
Opaque Pointers ConceptDefining Opaque StructsGetters and SettersValidation in SettersRecap: Secret Box2Objects and Methods
Structs as ObjectsThe 'Self' PointerConst CorrectnessPointer vs ValueHelper MethodsRecap: Point Manager5Project: Simple Bank Account
Project SetupImplementation of Account3Object Lifecycle
Constructor PatternDestructor PatternStack InitializationDeep CopyRecap: String Wrapper6Inheritance via Composition
Struct EmbeddingThe First Member RuleAccessing Parent MembersUpcastingRecap: Shape Hierarchy