Loading lessons...
Working with Strings in Memory
Working with Strings in Memory
C strings are arrays, so they also inherit array rules. Let's see the practical ones.
Strings need room
A string variable is a fixed-size array. Copying a longer string into a small buffer overflows it:
char small[5];
strcpy(small, "much too long!!"); // danger: overflow
Make the buffer big enough
char name[50];
strcpy(name, "Ada Lovelace");
String as memory
Strings share everything arrays share: start at index 0, contiguous bytes, and they "decay" to a pointer when passed around.
One more: string literal is read-only
char *p = "fixed text";
p[0] = 'X'; // often bad: modifying a string literal
Use a char array (not a pointer) if you'll modify the text.
TL;DR
- Strings are fixed-size arrays; match the buffer to the data.
- Copying too much memory is called overflow.
- Prefer a char array when you will modify the text.
- Know the length before you copy.