Try Embedded

Arrays and strings

Decay, bounds, safe copying, and parsing and formatting without the heap.

Arrays are not pointers, but they decay into them

An array is a block of elements with a size the compiler knows. In almost every expression, though, the array's name turns into a pointer to its first element. This is called decay, and it is why a function can never receive an array, only a pointer.

#include <stdio.h>
#include <stdint.h>

#define ARRAY_LEN(a) (sizeof(a) / sizeof((a)[0]))

static void takes_array(uint16_t samples[8]) {
  // The [8] is decoration: the parameter is really `uint16_t *samples`.
  printf("inside the function: sizeof = %u\n", (unsigned)sizeof samples);
}

int main(void) {
  uint16_t samples[8] = { 0 };
  printf("in main: sizeof = %u, elements = %u\n", (unsigned)sizeof samples, (unsigned)ARRAY_LEN(samples));
  takes_array(samples);
  return 0;
}

So every function that takes a buffer also takes its length. ARRAY_LEN works only where the real array is visible; applied to a pointer it silently gives a wrong answer.

Bounds are your job

C does not check array indices. Writing a[n] on an array of n elements overwrites whatever comes next in memory: another variable, a return address, a heap header. On a microcontroller there is no operating system to stop it, so the symptom appears somewhere else, later.

The simulator used here does check. Run this and read the message.

#include <stdint.h>

int main(void) {
  uint8_t buffer[4];
  for (int i = 0; i <= 4; i++) buffer[i] = 0;   // i == 4 is one past the end
  return 0;
}

Then change <= to < and run it again.

Pitfall: The classic off-by-one is <= in a loop over an array, or forgetting that a string of n characters needs n + 1 bytes.

Strings

A C string is an array of char ending in a zero byte, the terminator '\0'. Nothing stores the length; functions find the end by scanning for the zero.

DeclarationWhat you get
char s[] = "abc";A writable array of 4 bytes: a, b, c, \0
const char *s = "abc";A pointer to a literal in read-only memory
char s[8] = "abc";8 bytes; the unused ones are zero
char s[3] = "abc";3 bytes and no terminator: not a string
#include <stdio.h>
#include <string.h>

int main(void) {
  char name[] = "sensor";
  printf("sizeof = %u (capacity, includes the terminator)\n", (unsigned)sizeof name);
  printf("strlen = %u (characters before the terminator)\n", (unsigned)strlen(name));

  name[0] = 'S';                 // fine: this is our own array
  printf("%s\n", name);
  return 0;
}

String literals live in flash on a microcontroller. Writing to one is undefined behaviour, so point at them with const char *.

Copying safely

Most buffer overflows in C are string copies. Know what each function does when the source is too long.

FunctionBoundedAlways terminatesNotes
strcpy(dst, src)NoYesOverflows dst if src is longer
strncpy(dst, src, n)YesNoLeaves dst unterminated when src has n or more characters; pads with zeros otherwise
snprintf(dst, n, "%s", src)YesYesReturns the length it wanted to write, so truncation is detectable
memcpy(dst, src, n)YesNot a string functionFor known lengths; regions must not overlap
#include <stdio.h>
#include <string.h>

int main(void) {
  char small[6];
  const char *input = "temperature";

  int wanted = snprintf(small, sizeof small, "%s", input);
  printf("stored \"%s\", needed %d characters, truncated: %s\n",
         small, wanted, wanted >= (int)sizeof small ? "yes" : "no");

  char risky[6];
  strncpy(risky, input, sizeof risky);          // fills all 6 bytes, no terminator
  risky[sizeof risky - 1] = '\0';               // the line people forget
  printf("after strncpy and a manual terminator: \"%s\"\n", risky);
  return 0;
}

Parsing input you do not trust

Anything that arrives over a UART, from a file or from a network is untrusted. A parser must reject what it does not understand instead of guessing. atoi cannot report an error: it returns 0 for "abc" and has undefined behaviour on overflow.

A robust parser checks three things: that there is at least one digit, that every character is valid, and that the value stays in range as it accumulates.

#include <stdio.h>
#include <stdint.h>
#include <stdbool.h>

static bool parse_u8(const char *s, uint8_t *out) {
  if (*s == '\0') return false;                 // empty input
  unsigned value = 0;
  for (; *s; s++) {
    if (*s < '0' || *s > '9') return false;     // not a digit
    value = value * 10 + (unsigned)(*s - '0');
    if (value > 255) return false;              // out of range: stop before it can wrap
  }
  *out = (uint8_t)value;
  return true;
}

int main(void) {
  const char *inputs[] = { "42", "255", "256", "12a", "" };
  for (int i = 0; i < 5; i++) {
    uint8_t v = 0;
    bool ok = parse_u8(inputs[i], &v);
    printf("\"%s\" -> %s", inputs[i], ok ? "ok" : "rejected");
    if (ok) printf(" (%u)", v);
    printf("\n");
  }
  return 0;
}

Formatting without printf

printf pulls in several kilobytes of code and may use the heap, which a bootloader or a small MCU cannot afford. Converting a number to text by hand takes a few lines: peel off digits with % 10, which produces them in reverse, then write them out backwards.

#include <stdio.h>
#include <stdint.h>

static void u32_to_str(uint32_t v, char *out) {
  char tmp[10];
  int n = 0;
  do {                           // do-while so that 0 produces "0"
    tmp[n++] = (char)('0' + v % 10);
    v /= 10;
  } while (v);
  while (n) *out++ = tmp[--n];
  *out = '\0';
}

int main(void) {
  char text[11];
  u32_to_str(0, text);          printf("%s\n", text);
  u32_to_str(4294967295u, text); printf("%s\n", text);
  return 0;
}

For hexadecimal, index a lookup string with each nibble: "0123456789ABCDEF"[v >> 4] and [v & 0x0F].

Splitting a line in place

Text protocols such as NMEA and AT commands are comma-separated. The memory-free way to split them is to overwrite each delimiter with a terminator and keep a pointer to the start of each field. The fields then are ordinary strings inside the original buffer.

Avoid strtok for this. It treats consecutive delimiters as one, so empty fields vanish, and it keeps hidden static state, so it is not safe to use from an interrupt and the main loop at the same time.

Common mistakes

  • Forgetting the byte for the terminator when sizing a buffer.
  • sizeof of a pointer parameter, expecting the array's size.
  • Comparing strings with ==, which compares addresses. Use strcmp, which returns 0 when equal.
  • s[strlen(s) - 1] on an empty string, which reads the byte before the buffer.
  • Calling strlen in a loop condition, making an O(n) loop O(n^2).

Interview question: How does strlen differ from sizeof on a string?

Answer: sizeof is evaluated at compile time and gives the storage size of the array, including the terminator, or the size of a pointer if applied to one. strlen runs at run time and counts characters up to the first zero byte. For char s[16] = "hi", sizeof s is 16 and strlen(s) is 2.

Interview question: You must copy a string into a fixed 32-byte field. Which function do you use and why?

Answer: snprintf(dst, sizeof dst, "%s", src) if printf is available: it never overflows, always terminates and its return value reveals truncation. Without printf, a small strlcpy-style helper that copies at most size - 1 characters and then writes the terminator. Not strcpy, which is unbounded, and not bare strncpy, which can leave the field unterminated.

In the product: a GPS tracker

The tracker reads lines like $GPGGA,123519,4807.038,N,... from the receiver and picks out fields, into fixed buffers that can never overflow.

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

int main(void) {
  const char *line = "$GPGGA,123519,4807.038,N,01131.000,E,1,08,0.9,545.4,M";
  char field[16];
  const char *p = line;
  for (int n = 0; n < 2 && p; n++) p = strchr(p + 1, ',');   // to the second comma: the latitude follows it
  if (p) {
    size_t len = 0;
    while (p[1 + len] != ',' && p[1 + len] != '\0') len++;      // the field's length
    if (len >= sizeof field) len = sizeof field - 1;            // never overflow the buffer
    memcpy(field, p + 1, len);
    field[len] = '\0';
    printf("latitude: %s\n", field);
  }
  return 0;
}

Build it: text for a small screen

This is step 5 of the module project. The screen has room for 10 characters a line. Text is built into fixed-size char buffers, and a value that does not fit must never write past the end: that is how screens show garbage, and how firmware gets hacked.

Lab: Format numbers into fixed buffers safely

Write these without sprintf (it is not linked into this firmware, to save flash):

  • fmt_x10(buf, size, v_x10, unit) writes a tenths value and a unit, such as 23.5 km/h, into buf, which holds size bytes, and ends it with '\0'. It returns the number of characters written (not counting the '\0'). If the text and its '\0' do not fit, it writes nothing (just '\0' if size is at least 1) and returns -1.
  • str_copy(dst, size, src) copies a string into a buffer of size bytes, cutting it short if needed, and always ends it with '\0' (when size is at least 1). It returns the number of characters copied.

Going deeper

Interview question: How would you design a GPS tracker's parser so a corrupted or malicious sentence can never crash it?

Answer: Parse byte by byte with a state machine into fixed buffers with explicit length checks, reject a sentence on the first unexpected character or overlong field, verify the checksum before using any field, and never use functions that cannot bound their output. Fuzz it on a PC with random and truncated sentences, and treat the receiver as untrusted input.

Interview question: Why is strncpy not a safe replacement for strcpy?

Answer: strncpy does not add a null terminator if the source is at least as long as the limit, leaving the destination unterminated, and it pads with zeros otherwise, wasting time. Safer options are snprintf(dst, size, "%s", src), strlcpy where available, or a small helper that copies at most size-1 characters and always terminates. Always pass the destination's real size.

Interview question: Why can't a function find the length of an array passed to it?

Answer: An array argument decays to a pointer to its first element, so inside the function sizeof gives the pointer size, not the array size, and no length information is passed. The function needs the length as a separate parameter (or a terminator such as the null character in strings). This is why C APIs take a buffer and its size together.

Explain it: In your own words, explain how to parse untrusted input like a serial command safely.

Answer: Treat every byte as potentially wrong. Read into a fixed-size buffer while counting, and stop at the buffer size minus one so it can be null-terminated. Check the length and characters before using them, convert numbers with functions that report errors and range (strtol with an end pointer and errno) rather than atoi, check the result is within the allowed range, and reject anything unexpected instead of guessing. Never use the input as a format string or an unchecked index.