What is C String Parsing and Recursion- Online Embedded C Programming Classes

🚀 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 →

Free C Programming Course · Strings

C String Parsing and Recursion

Parse strings in C with sscanf, strtol and NUL patching, and walk strings with safe loops and recursion.

Text arrives in firmware as one long run of characters: a timestamp from a GPS module, a command typed on a console, a line from a configuration file. To parse strings in C reliably you need a handful of techniques that work without a heavy library: splitting by temporarily patching a NUL, reading numbers with sscanf and strtol, walking text with a loop or with recursion, and handling format strings with care. This lecture of our free C programming course covers each technique with tested code.

What You Will Learn

  • How to split a string in place by writing a NUL and then restoring the original character
  • How sscanf and strtol extract numbers, and how they differ
  • Why a pre-increment loop such as while (s[++i]) is a length bug waiting to happen
  • How to traverse a string recursively, forwards and backwards
  • Why printf(text) with untrusted text is dangerous

Prerequisites

Before starting, make sure the previous lectures on string pointers, offsets and appending are clear, along with basic recursion from the functions chapter of this free C tutorial. Examples compile with GCC 13 and -std=c11 -Wall -Wextra -Wformat-security.

How to Parse Strings in C by Splitting in Place

The easiest way to parse strings in C is to start small. Imagine a clock reading 14:35:07 stored in a character array. You want three integers. One classic trick needs no library call to split the text: overwrite each colon with a NUL byte. The single array then contains three tiny strings that start at offsets 0, 3 and 6. Each can be handed to atoi or strtol. When you are finished you put the colons back so the original text is intact for logging.

Patching colons with NUL to split one string into three

index012345678
original14:35:07\0
patched14\035\007\0
Pieces start at index 0, 3 and 6. Restore index 2 and 5 afterwards

Three Ways to Parse Strings in C

The program below reads the time three times with three different methods so that you can compare them. Each prints the same numbers.

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

int main(void)
{
    char t[] = "14:35:07";
    int h, m, s;

    t[2] = t[5] = '\0';
    h = atoi(t);
    m = atoi(t + 3);
    s = atoi(t + 6);
    t[2] = t[5] = ':';
    printf("patched : h=%d m=%d s=%d, restored=%s\n", h, m, s, t);

    if (sscanf(t, "%d:%d:%d", &h, &m, &s) == 3)
        printf("sscanf  : h=%d m=%d s=%d\n", h, m, s);

    {
        char *end;
        h = (int)strtol(t, &end, 10);
        m = (int)strtol(end + 1, &end, 10);
        s = (int)strtol(end + 1, &end, 10);
        printf("strtol  : h=%d m=%d s=%d\n", h, m, s);
    }
    return 0;
}
patched : h=14 m=35 s=7, restored=14:35:07
sscanf  : h=14 m=35 s=7
strtol  : h=14 m=35 s=7

Notice that the leading zero of 07 disappears in the output, because the value is now an integer rather than text. Now compare the techniques in practice.

TechniqueStrengthWeaknessGood for
NUL patching with atoiNo library parsing, very small codeModifies the buffer, atoi cannot report errorsTrusted fixed-format data
sscanfReadable format, checks how many fields matchedHeavier code size, needs care with stringsQuick tools, configuration lines
strtol with end pointerReports errors, no modification, cheapYou write the loop yourselfProduction embedded parsers

Tip: always check the return value of sscanf. It returns the number of fields converted, so comparing it with 3 above rejects input such as 14:xx:07 instead of using half-initialised variables.

String Length Loops: Pre-Increment Pitfall

A compact way to measure a string is while (s[++i]);. It looks clever, but increments before testing, so the first character is never examined. For any non-empty string the result matches the true length, because the loop stops at the NUL. For an empty string it tests s[1], which is outside the array, and the behaviour is undefined. The safe loop uses a post-increment or a for loop and starts at index zero.

#include <stdio.h>

static int len_pre(const char *s)
{
    int i = 0;
    while (s[++i])
        ;
    return i;
}

static int len_safe(const char *s)
{
    int i = 0;
    while (s[i])
        i++;
    return i;
}

int main(void)
{
    printf("pre-increment: %d\n", len_pre("firmware"));
    printf("safe version : %d\n", len_safe("firmware"));
    printf("safe on empty: %d\n", len_safe(""));
    return 0;
}
pre-increment: 8
safe version : 8
safe on empty: 0

Both functions agree for the word firmware, which hides the defect. We deliberately did not call len_pre(""), since that is the undefined case. A test suite for a string routine must always include the empty string, a one character string and the longest allowed string; those boundary cases are where such bugs live.

Walking Strings With Recursion

A string has a natural recursive shape: it is either empty or it is one character followed by a shorter string. Pointer arithmetic makes that literal, because s + 1 is the shorter string. The first function prints characters until it meets a stop character or the end. The second prints the text in reverse by recursing first and printing on the way back.

#include <stdio.h>

static void print_until(const char *s, char stop)
{
    if (*s == '\0' || *s == stop)
        return;
    putchar(*s);
    print_until(s + 1, stop);
}

static void print_reversed(const char *s)
{
    if (*s == '\0')
        return;
    print_reversed(s + 1);
    putchar(*s);
}

int main(void)
{
    print_until("AT+CSQ;extra", ';');
    printf("\n");
    print_reversed("UART");
    printf("\n");
    return 0;
}
AT+CSQ
TRAU

Notice the base case of print_until: it tests the NUL as well as the stop character. A version that tests only the stop character runs off the end if the stop character is missing, which is a very common bug. In print_reversed the order of the two statements after the base case is the whole trick: because the recursive call comes before putchar, the characters are printed while the calls unwind.

Call sequence of print_reversed on the word UART

call U→call A→call R→call T→NUL base case
print T→print R→print A→print U
Calls go forward through the string; printing happens while returning

Warning: every recursive call uses stack. A string of one thousand characters means one thousand frames. On a microcontroller with a small stack, prefer a loop unless the string is known to be short.

Format Strings: When the Text Is the Format

A format string does not have to be a literal. You can store one in a pointer and pass it to printf, which is useful for configurable log lines. The danger arrives when the data itself is used as the format. If the text contains conversion specifiers such as %d or %s, printf will try to read arguments that you never supplied.

#include <stdio.h>

int main(void)
{
    const char *fmt = "node=%s id=%d\n";
    const char *text = "battery 100%d low";

    printf(fmt, "alpha", 7);
    printf("%s\n", text);
    printf(text);
    printf("\n");
    return 0;
}

GCC warns about the unsafe call when -Wformat-security is on:

p46d.c:10:5: warning: format not a string literal and no format arguments [-Wformat-security]
   10 |     printf(text);
      |     ^~~~~~

The output on our machine was:

node=alpha id=7
battery 100%d low
battery 1001464446995 low

The second line is correct because %s prints the text literally. The third line is the bug: printf interpreted %d inside the data and printed a stray number taken from a register or the stack. That number will differ from run to run. In a real device the same flaw can leak memory with %x or even write memory with %n, so the golden rule is simple: the format must be a fixed literal, and data goes in as arguments. If you only need to print text, use fputs or puts.

Common Mistakes When You Parse Strings in C

MistakeEffectFix
Not restoring a patched NULLater code sees a truncated stringWrite the original delimiter back
Ignoring the return value of sscanfUses uninitialised variablesCompare with the expected field count
Using atoi on untrusted dataNo error detectionUse strtol and check the end pointer
Pre-increment length loopUndefined behaviour on empty inputTest first, then increment
Recursion without NUL testRuns past the end of the stringAlways test for '\0' in the base case
printf(user_text)Format string vulnerabilityUse printf("%s", user_text)

Best Practices, Performance and Security

  • Validate every field: count, range and trailing characters, not only the happy path.
  • Prefer strtol and its end pointer for firmware, and reserve sscanf for tools and prototypes.
  • Parse a read-only view when you can; patch a copy when you must.
  • Use loops instead of recursion on small stacks.
  • Build with -Wformat -Wformat-security, and never use data as a format string.

Performance: when you parse strings in C, sscanf brings in a lot of library code, which may matter on small flash sizes. The strtol approach touches each character once. Security: text parsers are an obvious attack surface for any device reachable over UART, USB or radio, so fuzzing them with random and truncated input is time well spent.

Summary and Key Takeaways

  • To parse strings in C, placing a NUL splits one buffer into several strings; restore the delimiter afterwards.
  • sscanf is convenient, strtol is precise, and both should have their results checked.
  • Loop conditions that increment first can skip the first character or the NUL check.
  • Recursion on strings needs a NUL-aware base case and costs stack.
  • Never let data act as the format string.

Conclusion

Learning to parse strings in C is where string knowledge becomes real engineering. The techniques here, in-place splitting, checked numeric conversion, safe traversal and format discipline, show up again and again in bootloader menus, modem drivers and protocol stacks. As an exercise, write a function that parses YYYY-MM-DD using only strtol and the end pointer, rejecting any input with extra characters. Then run it against an empty string, a missing field and a value with letters. That single task practises everything in this free embedded C course lecture and gives you a solid piece for any embedded C programming portfolio. Our final lecture of this set puts everything together with a lab, a quiz and interview questions.

Frequently Asked Questions

How do I parse strings in C without a library?

Walk the text with a pointer, and overwrite delimiters with NUL to split it into several strings in place. Convert numeric pieces with strtol, then restore the delimiters if the original text is still needed.

Is sscanf or strtol better for embedded code?

strtol is usually better in firmware because it is smaller, never modifies the input and reports exactly where it stopped. sscanf is more convenient but pulls in more code and is easier to misuse.

Why does while (s[++i]) fail for an empty string?

The pre-increment makes the first test look at index 1. For an empty string that index is beyond the terminator, so the read is out of bounds and the behaviour is undefined.

How does recursion work on a C string?

A string is either empty or a character followed by a shorter string, and s + 1 is that shorter string. The base case checks for the NUL terminator, and the recursive call processes the remainder.

Why is printf(user_input) dangerous?

If the input contains conversion specifiers, printf reads arguments that were never supplied and can leak or corrupt memory. Always use printf(“%s”, user_input) or puts instead.

Do I need to restore the characters I replaced with NUL?

Yes, if other code will use the original string. Until you restore them, the buffer holds several short strings and the original text appears truncated.

How do I check that sscanf succeeded?

Compare its return value with the number of conversions you expect. A smaller value means some fields were not matched and their variables were not set.

Keep Going With the Free C Course

EmbeddedPathashala is a free C programming course and free embedded C course built for students. Practice every example on your own machine, then move on to the next lecture.

💬 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 →