What are Dynamic Strings with malloc- Free Embedded Systems and C Programming Course

🚀 Learn BLE on Linux (BlueZ) – Programming Part 1

Hands-on Bluetooth Low Energy course. Special price: ₹399

Enroll Now on Udemy →
💬 Need help or career guidance? Ask us!Contact Us →

PREV_LEC | NEXT_LEC

Free Embedded C Course • Strings • Lecture 26

Dynamic Strings with malloc

Read text of unknown length, allocate exactly the right number of bytes for each string, and store the addresses in an array of pointers. A hands-on lecture in our free C programming course.

When you do not know how long a string will be, a fixed buffer either wastes memory or overflows. Dynamic strings with malloc solve this: read the text, measure it, allocate exactly strlen + 1 bytes, and keep the address in an array of pointers. This is a core skill in embedded C programming on Linux-based devices and a favourite interview topic. In this free C tutorial lecture you will build a small device name registry step by step.

What You Will Learn

  • Why a pointer slot needs real memory before text can be copied in
  • How to read a line safely with fgets instead of gets
  • The read, measure, allocate, copy pattern
  • Why the allocation size is strlen(s) + 1
  • How to free every string and avoid dangling pointers

Prerequisites

You should know the array-of-pointers layout from the last two lectures, and the basics of malloc and free from the Pointers chapter (cp8_45 onwards).

The Read, Measure, Allocate, Copy Pattern

An unset pointer slot cannot receive text. The cure is a four-step routine that you will repeat in countless programs:

  1. Read the text into a temporary buffer of known size
  2. Measure its length with strlen
  3. Allocate length + 1 bytes, the extra byte holds the terminator
  4. Copy the text into the new block and store the address in the slot
One loop iteration, step by step
1 Read → line[64] = “spi1\n”
2 Trim → line[64] = “spi1”
3 Allocate → malloc(strlen + 1) = 5 bytes
4 Copy and store → names[2] = new block

Why the plus one

strlen("spi1") is 4 because it does not count the terminator. The string needs 5 bytes. Forgetting the extra byte writes one byte past the block, a classic heap overflow.

Why Not gets

Older books use gets(str) to read a line. That function has no size limit, so any long input overflows the buffer. It was removed from the language in C11. Use fgets(buffer, sizeof buffer, stdin). It stops at the size limit and keeps the newline character, so we strip the newline ourselves with strcspn.

Complete Program: Device Name Registry

Save as name_registry.c:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX_NAMES 4
#define LINE_LEN  64

int main(void)
{
    char *names[MAX_NAMES] = { NULL };
    char  line[LINE_LEN];
    int   count = 0;

    while (count < MAX_NAMES && fgets(line, sizeof line, stdin) != NULL) {
        line[strcspn(line, "\n")] = '\0';          /* drop the newline */

        names[count] = malloc(strlen(line) + 1);   /* +1 for the '\0' */
        if (names[count] == NULL) {
            fprintf(stderr, "out of memory\n");
            break;
        }
        strcpy(names[count], line);
        count++;
    }

    for (int i = 0; i < count; i++)
        printf("%d: %-16s (%zu bytes allocated)\n",
               i, names[i], strlen(names[i]) + 1);

    for (int i = 0; i < count; i++) {
        free(names[i]);
        names[i] = NULL;
    }
    return 0;
}

Build and run

gcc -std=c11 -Wall -Wextra -pedantic -o name_registry name_registry.c
printf 'uart0\ni2c-controller\nspi1\ngpio\n' | ./name_registry

Expected output:

0: uart0            (6 bytes allocated)
1: i2c-controller   (15 bytes allocated)
2: spi1             (5 bytes allocated)
3: gpio             (5 bytes allocated)

Every string got exactly the memory it needed: 5 characters plus terminator is 6, 14 characters plus terminator is 15, and so on. No byte is wasted, which a grid of fixed rows could not achieve.

Line by line

CodePurpose
char *names[MAX_NAMES] = { NULL };All slots start as NULL, so an unused slot is never a random address
fgets(line, sizeof line, stdin)Reads at most 63 characters, always terminates the buffer
strcspn(line, "\n")Finds the newline position, writing '\0' there removes it
malloc(strlen(line) + 1)Exact-size block for this one string
NULL checkmalloc can fail, always test before copying
free(names[i]); names[i] = NULL;Releases memory and prevents use of a dangling pointer
Heap picture after the program reads four names
names[0] → uart0\0 6 bytes
names[1] → i2c-controller\0 15 bytes
names[2] → spi1\0 5 bytes
names[3] → gpio\0 5 bytes

A Longer Array of Pointers at Run Time

Our table has a fixed 4 slots. If even the number of strings is only known at run time, allocate the pointer array too: char **names = malloc(n * sizeof *names);. The matching clean-up frees every string first and the array last. Doing it in the opposite order loses the addresses and leaks memory.

Real-World Use Cases

  • A Linux gateway storing configuration keys read from a file
  • A shell parsing a command line into separate argument strings
  • A log collector keeping the last few messages of unequal length
  • A test tool loading device names from a text list

Common Mistakes and Troubleshooting

MistakeSymptomFix
malloc(strlen(s)) without the plus oneRandom crashes or corrupted heapAlways add 1
Not checking malloc resultCrash on low memoryTest for NULL
Forgetting freeMemory slowly grows, long running device failsOne free per malloc, in a loop
Double freeAbort from the allocatorSet the pointer to NULL after free
Using getsBuffer overflow, removed in C11Use fgets
Not stripping newlineNames contain a hidden \n, comparisons failUse strcspn

A good tool for hunting these bugs is the address sanitizer: build with -fsanitize=address -g and run again. It reports leaks and overflows with line numbers.

Performance and Embedded Considerations

  • Many small allocations fragment the heap, which matters on devices running for months
  • Bare-metal firmware often avoids malloc completely and uses fixed pools
  • Each block has allocator overhead, so very short strings cost more than their length

Security Considerations

Never trust the length of external input. Bound every read with the buffer size, check allocation failures, and never copy into a block smaller than strlen + 1. Input from a network or file is hostile by default.

Best Practices

  • Initialise pointer arrays to NULL
  • Check every allocation
  • Free in a loop, then set slots to NULL
  • Pair each malloc with exactly one free in the same module
  • Test with the address sanitizer before shipping

Try It Yourself: Extend the Registry

  1. Print the total. Add a running sum of strlen(names[i]) + 1 and print it. For the sample input the total is 31 bytes, compared with 4 times 64 equals 256 bytes if every name had used a full line buffer.
  2. Reject empty lines. If line[0] is '\0' after trimming, skip the allocation. Real configuration files contain blank lines.
  3. Find a name. Write a loop that uses strcmp(names[i], "spi1") == 0 to look for a device and print its index. This is the same technique a command shell uses to match typed words.
  4. Run it under the sanitizer. Build with -fsanitize=address -g, then remove one free call and run again. The leak report shows exactly how many bytes were lost, a useful picture of what a missing free costs.

Doing these four tasks turns the pattern from something you have read into something your fingers remember, and that is what interviewers look for when they ask you to write a string routine on a whiteboard.

Summary and Key Takeaways

  • A pointer slot needs real memory before you copy text into it
  • Use read, measure, allocate, copy
  • Allocate strlen + 1, never strlen
  • Use fgets, never gets
  • Free each string, then clear the slot

You can now store text of any length in an array of pointers. Next, we use another pointer array trick: lookup tables that turn a number into a message.

Frequently Asked Questions

Why do I allocate strlen plus one bytes?

strlen does not count the terminating null character, but the string needs it.

Why is gets dangerous?

It cannot limit input size, so long input overwrites memory. It was removed in C11.

Do I free the array of pointers or each string?

Free each string that was allocated. If the pointer array itself was allocated, free it last.

What happens if malloc returns NULL?

Memory is exhausted. Report the error and stop or clean up. Copying into NULL crashes.

Can I use malloc on a microcontroller?

It is possible with a heap configured in the linker, but many safety-critical projects forbid it.

Is there a shortcut to duplicate a string?

Yes, strdup does allocate and copy in one call. It became part of standard C in C23, and POSIX systems have long provided it.

Free Embedded C Programming Course

Next in this free embedded C course: lookup tables with arrays of strings.

PREV_LEC | NEXT_LEC

💬 Need help or career guidance? Ask us!Contact Us →

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

×

🚀 BLE on Linux (BlueZ)

Hands-on course. Only ₹399

Enroll Now →