Menu
Coddy logo textTech

Recap: String Wrapper

Part of the Object Oriented Programming section of Coddy's C journey — lesson 16 of 61.

challenge icon

Challenge

Easy

Let'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 a StringObject struct with a single member: char *text (a pointer to a dynamically allocated string). Also declare three functions:
    • create_string — takes a const char * input and returns a pointer to a newly allocated StringObject
    • print_string — takes a const StringObject * and displays the stored text
    • free_string — takes a StringObject * and releases all allocated memory
    Use include guards with the symbol STRINGOBJ_H.
  • stringobj.c: Implement all three functions. Your constructor should allocate memory for the struct, then allocate memory for the text (remember strlen plus one for the null terminator), and copy the input string. Your destructor must free in reverse order—the internal text buffer 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:

Freed

For example, with input Hello World, the output would be:

Text: Hello World
Freed

Try 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