Recap: String Wrapper
Part of the Object Oriented Programming section of Coddy's C journey — lesson 16 of 61.
Challenge
EasyLet's build a StringObject module that wraps a dynamically allocated character array. This recap challenge brings together the complete object lifecycle—constructor, read-only method, and destructor—all working together to manage memory safely.
You'll create three files:
stringobj.h: Declare aStringObjectstruct with a single member:char *text(a pointer to a dynamically allocated string). Also declare three functions:create_string— takes aconst char *input and returns a pointer to a newly allocated StringObjectprint_string— takes aconst StringObject *and displays the stored textfree_string— takes aStringObject *and releases all allocated memory
STRINGOBJ_H.stringobj.c: Implement all three functions. Your constructor should allocate memory for the struct, then allocate memory for the text (rememberstrlenplus one for the null terminator), and copy the input string. Your destructor must free in reverse order—the internaltextbuffer first, then the struct itself. Include a NULL check in your destructor for safety.main.c: Use your module to create a string object, display its contents, then properly clean up.
You will receive one input: a text string to store in your StringObject.
In your main file, create a StringObject with the provided text, print its contents, free the memory, then print a confirmation message.
The print_string function should output in this format:
Text: {text}After freeing, print:
FreedFor example, with input Hello World, the output would be:
Text: Hello World
FreedTry it yourself
#include <stdio.h>
#include "stringobj.h"
int main() {
char input[256];
fgets(input, sizeof(input), stdin);
// Remove newline if present
int len = 0;
while (input[len] != '\0') len++;
if (len > 0 && input[len - 1] == '\n') {
input[len - 1] = '\0';
}
// TODO: Create a StringObject with the input text
// TODO: Print the string using print_string
// TODO: Free the StringObject using free_string
// TODO: Print "Freed" to confirm cleanup
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