Skip to content
Codescope

Strings in memory

C has no string type. It has bytes, and an agreement about where they stop.

deep11 min7 steps

Before you start

Most languages have a String type — an object that knows its own length. C does not. In C, a string is just a series of char bytes in memory, terminated by a single zero byte (\0) that means "the string ends here".

This convention is why strlen has to walk the string counting characters until it hits the zero, and why forgetting the terminator turns your string into whatever bytes happen to sit after it in memory.

This lesson lays out a string byte by byte, shows the terminator, and walks through what goes wrong when you copy a string into a buffer that is too small — the classic **buffer overflow**.

Stack bytes

one square = one char
buf[6]
h
0x7ffc0a10
e
0x7ffc0a11
l
0x7ffc0a12
l
0x7ffc0a13
o
0x7ffc0a14
\0
0x7ffc0a15
6 bytes you own

Declare buf[5] instead and there is no room for the terminator — the array is no longer a string.

Step 1 of 7. "hello" is five characters and six bytes. `char buf[6] = "hello";` copies five characters into the array and adds a sixth byte: `'\0'`, the null terminator. Nothing in C records that this array is 5 long. The `\0` *is* the length — every string function finds the end by scanning for it.

01 / 07

Step 01 / 07

"hello" is five characters and six bytes

char buf[6] = "hello"; copies five characters into the array and adds a sixth byte: '\0', the null terminator.

Nothing in C records that this array is 5 long. The \0 *is* the length — every string function finds the end by scanning for it.

strings-in-memory.cC
#include <stdio.h>#include <string.h>int main(void) {    char  buf[6] = "hello";    char *lit    = "hello";    printf("%zu\n", strlen(buf));    buf[5] = '!';    printf("%s\n", buf);    strcpy(buf, "hello world");    return 0;}