Strings in memory
C has no string type. It has bytes, and an agreement about where they stop.
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 charDeclare 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.
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.
#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;}