In C, strings are terminated by a null character '\0'. Your task is to implement a custom strlen() function that calculates the length of a string without using any built-in functions.
You will be given a string of maximum of 100 characters. Return the number of characters before the null terminator.
Example-1
Input: "Embedded"
Output: 8
Example-2
Input: "C is powerful"
Output: 13
Example-3
Input: ""
Output: 0
A string in C is an array of characters terminated by a null character ('\0').
char msg[ ] = "OK"; // Stored as: ['O', 'K', '\0']char s[ ] = "Hi";
Index: 0 1 2
Value: 'H' 'i' '\0'You must always account for the null terminator when allocating space.
char name[10]; // Can store 9 characters + '\0'
| Operation | Description |
|---|---|
strlen() | Count length (excluding '\0') |
strcpy() | Copy string |
strcmp() | Compare two strings |
strchr() | Search for a character |
strcat() | Concatenate (⚠️ risky — can cause overrun!) |
atoi() / strtol() | Convert string to integer |
In firmware, we often reimplement minimal-safe versions of these.
Useful when parsing commands, serial input, file systems, etc.
| Check | Function | ASCII Range |
|---|---|---|
| Is digit? | isdigit(c) | '0' to '9' |
| Is alpha? | isalpha(c) | 'A'–'Z', 'a'–'z' |
| Is alphanumeric? | isalnum(c) | Digit or alpha |
| To upper/lower | toupper(c), tolower(c) | Changes case |
You can implement these yourself using ASCII values.
int is_digit(char c) {
return (c >= '0' && c <= '9');
}Firmware often receives comma-separated or command-style input via UART or SPI:
char input[ ] = "SET,12,ON";You may need to:
Use functions like:
strtok() (not always safe)| Problem | Example / Notes |
|---|---|
| Null terminator missing | Causes garbage output, memory overread |
Buffer overflow in strcpy() | Common cause of firmware bugs |
Unsafe use of strcat() | Overwrites adjacent memory |
| Improper parsing | Fails if input format changes |
| Memory-inefficient operations | Prefer minimal parsing logic |
| Pitfall | What to Do |
|---|---|
| ❌ Forgetting '\0' terminator | Always allocate +1 byte for strings |
| ❌ Using strcpy blindly | Prefer safer copy functions with limit |
| ✅ Use sizeof(arr) wisely | Only works for stack arrays, not pointers |
| ✅ Parse manually for safety | Avoid strtok() if reliability matters |
| ✅ Reuse char arrays where possible | Minimize static memory usage |