🚀 Learn BLE on Linux (BlueZ) – Programming Part 1
Hands-on Bluetooth Low Energy course. Special price: ₹399
Enroll Now on Udemy →C Strings Lab and Quiz
Chapter 9, Lecture 12 of the free C programming course: command parser lab, quiz and interview questions
This lab brings together everything from the last four lectures of our free C programming course: embedded C string functions used together in one small program. You will build a console command parser that reads a line with fgets(), cleans it, measures it with strlen(), matches it with strcmp() and saves it with a bounded copy. It is the same structure that runs on thousands of real devices, and it is the best finish to this part of the free C tutorial.
After the lab you will find a ten-question quiz, four practice challenges and twelve interview questions on strings in C programming for embedded systems. Try each one before opening the answer, because recall is what makes embedded C string functions stick.
What You Will Learn
- How to combine fgets, strcspn, strlen, strcmp and snprintf in one working program
- How a command parser is structured: read, clean, validate, dispatch
- How to move the same logic from a PC terminal to a UART on a microcontroller
- How to test your understanding with a quiz and real interview questions
Prerequisites
Lectures 8 to 11 of this free embedded C course: reading strings, strlen, strcmp and copying strings. Every function used below was explained there.
Lab: Embedded C String Functions in Action
The goal is a prompt that accepts the commands help, led on, led off, ver and quit, complains about anything else, ignores blank lines, and remembers the last valid line it received. The flow below is the pattern to memorise.
The source code
#include <stdio.h>
#include <string.h>
#define LINE_MAX_LEN 40
static char last_cmd[LINE_MAX_LEN];
static void handle(const char *cmd)
{
if (strcmp(cmd, "help") == 0)
puts("commands: help, led on, led off, ver, quit");
else if (strcmp(cmd, "led on") == 0)
puts("LED -> ON");
else if (strcmp(cmd, "led off") == 0)
puts("LED -> OFF");
else if (strcmp(cmd, "ver") == 0)
puts("fw 1.0.3");
else
printf("unknown command: '%s'\n", cmd);
}
int main(void)
{
char line[LINE_MAX_LEN];
for (;;) {
printf("ep> ");
if (fgets(line, sizeof line, stdin) == NULL)
break;
line[strcspn(line, "\r\n")] = '\0';
if (strlen(line) == 0)
continue;
if (strcmp(line, "quit") == 0)
break;
snprintf(last_cmd, sizeof last_cmd, "%s", line);
handle(last_cmd);
}
printf("last command was: '%s'\n", last_cmd);
return 0;
}
Build and run
$ gcc -std=c17 -Wall -Wextra -o ex12_cmdparser ex12_cmdparser.c
$ ./ex12_cmdparser
A sample session (the text after each ep> prompt is what you type):
ep> help
commands: help, led on, led off, ver, quit
ep> led on
LED -> ON
ep> led off
LED -> OFF
ep> reboot
unknown command: 'reboot'
ep>
ep> ver
fw 1.0.3
ep> quit
last command was: 'ver'
How it works
| Step | Code | Why it is there |
|---|---|---|
| Bounded read | fgets(line, sizeof line, stdin) | Cannot overflow; returns NULL on end of input so the loop can exit |
| Clean | line[strcspn(line, "\r\n")] = '\0' | Removes newline, and carriage return from terminals that send both |
| Skip blanks | strlen(line) == 0 | An empty line is not an error |
| Remember | snprintf(last_cmd, sizeof last_cmd, "%s", line) | Bounded copy that always terminates |
| Match | strcmp(cmd, "led on") == 0 | Compares contents, not addresses |
Notice that quit is handled before the copy, which is why the final message reports ver, the last command that was actually executed. Notice also that the program never calls strcpy: the one copy it needs is bounded.
Porting the lab to a UART
On a microcontroller you replace fgets with a function that follows the same contract but takes bytes from the serial port. The version below is a sketch: uart_getc() stands for whatever blocking receive function your board support package provides.
size_t uart_read_line(char *buf, size_t size)
{
size_t n = 0;
for (;;) {
int c = uart_getc(); /* blocks until a byte arrives */
if (c == '\r' || c == '\n')
break; /* end of line */
if (n + 1 < size) /* keep room for the terminator */
buf[n++] = (char)c; /* extra characters are dropped */
}
buf[n] = '\0';
return n;
}
Everything after the read, the cleaning, matching and copying, stays exactly as written. That is the payoff of learning the standard contract first.
Blocking reads stall firmware
A loop that waits forever for a byte starves the rest of your system. In production code, fill a ring buffer from the UART interrupt and let the main loop poll it, or run the console in its own RTOS task.
Common Mistakes in the Lab
- Matching before stripping the newline, so
helpnever equalshelp\n. - Using
strcpyforlast_cmdand overflowing the 40-byte buffer when a long line arrives. - Writing
if (strcmp(cmd, "ver"))and getting the logic inverted. - Printing the user’s line with
printf(line), which lets the user inject format specifiers.
Best Practices for Embedded C String Functions
- One place for input cleaning; one place for dispatch.
- A table of command names and handlers instead of a growing chain of if statements, once you have more than five commands.
- Always state the maximum line length as a named constant.
- Reject over-long lines clearly instead of silently truncating them.
Quiz: Embedded C String Functions
Choose one answer for each question, then open the answer to check yourself.
What does
strlen("embedded")return?- 7
- 8
- 9
- It depends on the array size
Show answer
B. The word has 8 characters; the terminator is not counted.
For
char buf[20] = "abc";what aresizeof bufandstrlen(buf)?- 20 and 3
- 3 and 3
- 20 and 4
- 4 and 3
Show answer
A. sizeof reports the 20-byte array, strlen counts the 3 characters before the terminator.
Which call reads a whole line, spaces included, without risking overflow?
- gets(buf)
- scanf(“%s”, buf)
- fgets(buf, sizeof buf, stdin)
- puts(buf)
Show answer
C. gets was removed in C11, scanf with %s stops at whitespace, puts only prints.
What is the sign of
strcmp("Zed", "apple")on an ASCII system?- Positive
- Zero
- Negative
- Undefined
Show answer
C. Capital letters have smaller ASCII codes than lowercase ones, so Zed sorts first.
Which test correctly checks that strings
aandbare equal?- a == b
- strcmp(a, b) == 0
- strcmp(a, b) == 1
- strlen(a) == strlen(b)
Show answer
B. strcmp returns zero for equal contents. Equal length does not mean equal text, and == compares addresses.
How many bytes must the destination of
strcpy(dst, src)provide?- strlen(src)
- strlen(src) + 1
- sizeof src
- strlen(src) – 1
Show answer
B. One extra byte holds the copied terminator.
What does fgets do with the newline typed by the user?
- Discards it
- Stores it in the buffer if it fits
- Replaces it with a space
- Returns it separately
Show answer
B. fgets keeps the newline, which is why you usually remove it yourself.
What does
strncpy(dst, "ABCDEFG", 4)do to the terminator?- Adds it at dst[4]
- Adds it at dst[3]
- Writes none
- Writes two
Show answer
C. When the source is as long as the limit, no terminator is written.
What type does strlen return?
- int
- unsigned char
- size_t
- long double
Show answer
C. size_t, an unsigned type; print it with %zu.
What happens with
char *p = "abc"; p[0] = 'x';?- It changes the text safely
- Undefined behaviour, the literal is read-only
- A compile error always
- It copies the string
Show answer
B. The pointer aims at read-only text; use a char array if you need to modify it.
Practice Challenges
- Add a toggle. Add a
led togglecommand that flips a variable, and print the new state. Hint: keep the LED state in astatic int. - Ignore case. Make
LED ONwork. Hint: write a small function that converts the line to lowercase withtolower()before matching, remembering to cast each char tounsigned char. - Command table. Replace the if chain with an array of structures holding a command name and a function pointer, and loop through it with strcmp.
- Echo with arguments. Add
echo hello worldthat prints everything after the first five characters. Hint: check the prefix withstrncmp(line, "echo ", 5)and printline + 5.
Interview Questions on Embedded C String Functions
These are the string questions that come up again and again in embedded C interviews. Say your answer aloud first, then compare.
1. What is the difference between strlen and sizeof for a character array?
sizeof is a compile-time operator giving the storage size of the object in bytes. strlen is a run-time function that counts characters before the first terminator. For a pointer, sizeof gives the pointer size, not the text length.
2. Why can’t you compare two strings with ==?
Strings are addresses, so == compares the pointers. Two equal texts at different addresses compare unequal. Use strcmp and test for zero.
3. Why was gets() removed from the standard?
It has no way to limit how much it writes, so any long input overflows the buffer. It was removed in C11. Use fgets with the buffer size.
4. What does strcmp guarantee about its return value?
Only the sign: negative, zero or positive. The magnitude is implementation-defined, so never compare it with a specific number.
5. What is the difference between char *p = "abc" and char a[] = "abc"?
The pointer refers to a read-only literal that must not be modified. The array is a writable copy that lives in your own storage. sizeof also differs: pointer size versus 4 bytes.
6. Implement strlen without the library.
Walk a pointer until it reaches the terminator and subtract the start: const char *s0 = s; while (*s) s++; return s - s0; with a size_t return type.
7. What are the dangers of strcpy and what are the alternatives?
It does not check the destination size, so a long source overflows it. Alternatives are snprintf, strlcpy where available, or memcpy after validating the length. strncpy does not terminate on truncation, so it is not a drop-in fix.
8. Why can strlen(a) - strlen(b) < 0 never be true?
strlen returns the unsigned type size_t, so the subtraction wraps around to a huge positive value instead of going negative. Compare the lengths directly.
9. How do you safely remove the newline that fgets leaves in the buffer?
buf[strcspn(buf, "\n")] = '\0'; works whether or not a newline is present, and it is safe on empty strings.
10. How would you parse commands from a UART without malloc?
Fill a fixed-size line buffer from a ring buffer, always reserve one byte for the terminator, strip the line ending, then match with strcmp against a constant table of handlers. Reject over-long lines explicitly.
11. What is the difference between memcpy and memmove?
memcpy requires that the regions do not overlap. memmove handles overlap correctly, at a small speed cost.
12. Why should you not compare passwords with strcmp?
strcmp returns at the first differing byte, so its running time leaks how much of the guess was right. Use a constant-time comparison for secrets.
Key takeaways
- Real command parsers combine read, clean, validate and dispatch; each step uses one of the embedded C string functions you learned.
- Bounded input and bounded copies remove the most dangerous class of C bugs.
- The same logic runs on a PC terminal and on a UART with only the read function replaced.
- Be ready to explain strlen versus sizeof, strcmp return values and strcpy safety in interviews.
Conclusion
You have now covered reading, measuring, comparing and copying strings, and you have used all four in one working program. That is the core of the embedded C string functions every firmware engineer uses daily. The rest of the chapter extends these ideas with more library functions and with string arrays. Keep this lab program, extend it with the challenges above, and you will have a debug console you can reuse on every project.
Frequently Asked Questions
Can I run this lab on a microcontroller?
Yes. Replace fgets with a UART line reader such as the sketch shown, and replace printf and puts with your serial output function. The matching and copying code does not change.
How long should the line buffer be?
Long enough for your longest valid command plus the terminator. Forty bytes is plenty for short commands; define the size as a named constant.
Why does the lab ignore empty lines?
Users press Enter by accident, and some terminals send an extra line ending. Skipping empty lines keeps the console quiet.
Should I use a command table instead of if statements?
Once you have more than a handful of commands, yes. A table is shorter, easier to extend and easy to test.
Where can I practice more embedded C string problems?
Extend this lab with the four challenges, then continue with the next lectures of this free embedded C course, which cover string arrays and more library functions.
Topics Covered
Practise Embedded C for Free
Finished the lab? Extend it with the four challenges, then carry on through the free C programming course with the next chapter lecture.

2 Comments