Introduction

In C, a string is just an array of characters terminated with a null character '\0'. That’s it — no fancy object, just memory with a contract.

char name[] = "Alice";
// = {'A', 'l', 'i', 'c', 'e', '\0'};

Declaring Strings

1. String Literal

Stored in Flash/ROM, typically read-only. You must not modify this.

char* s = "Hello";
// Stored in .rodata (Flash), pointer is in RAM
// s[0] = 'h'; // Undefined behavior

Use const char* s = "Hello"; — makes intent clear.

2. Character Array

Stored in RAM, modifiable.

char s[] = "Hello";
// Copied from Flash to RAM at runtime
// s[0] = 'h'; // Allowed

Memory Mapping of Strings

DeclarationLocationModifiable
char* s = "abc";Flash (read-only)
char s[] = "abc";RAM
const char* s = "abc"Flash (safe)

String literals are stored in Flash, but if copied to char[], they occupy both Flash and RAM.


Common String Functions

Refer Commonly Used String‑Handling Functions for detailed explanation.

FunctionDescription
strlen(s)Get string length (excludes \0)
strcpy(dest, src)Copy string
strncpy(dest, src, n)Copy at most n chars
strcat(dest, src)Append string
strcmp(a, b)Compare two strings (0 if equal)
strncmp(a, b, n)Compare first n chars
strchr(s, ch)First occurrence of char ch in s
strrchr(s, ch)Last occurrence
strstr(a, b)First occurrence of string b in a
strtok(s, delim)Tokenize using delimiter
strcspn(s, set)Index of first match in set

Embedded Use Cases

1. UART Buffers

Strings are used as receive buffers for UART/SPI/USB.

volatile char rx_buf[64]; // DMA-compatible buffer

2. Command Parsing

For example, parsing "SET LED ON" via sscanf() or strtok().

3. Flash Lookup Tables (LUT)

const char* modes[] = {"ON", "OFF", "AUTO"};

Tips & Best Practices

  • Use const for string literals to avoid accidental modification.

  • Always ensure enough space for \0.

  • Avoid dynamic memory unless absolutely required (malloc).

  • In embedded, avoid strtok() in ISRs or multitasking environments.

  • When using DMA or ISR with buffers, mark as volatile.