Arrays are boxes in a row
3 min readAn a contiguous block of memory that holds a fixed number of values of one type is the most basic container in C. Each value inside it is an element, and you reach an element by its the zero-based position of an element within an array. The declaration states the type and the number of elements.
int a[5]; /* 5 ints, uninitialized */
float temps[24]; /* 24 floats */
Indices start at 0, so a[5] has valid indices 0 through 4. The first element is a[0], the last is a[4]. This zero base is not a quirk of taste: a[i] means "start at the address of a and move i elements forward", so index 0 is the element at the starting address.
You can initialize an array when you declare it. If you give fewer values than the size, the rest are filled with zero. If you leave the size out, the compiler counts the values for you.
int a[5] = {22, 37, 3490, 18, 95};
int b[5] = {22, 37}; /* {22, 37, 0, 0, 0} */
int c[] = {1, 2, 3}; /* size 3 */
int z[100] = {0}; /* all 100 zeroed */
The array name has a size you can measure with sizeof, but only in the scope where it was declared. On a typical 64-bit Linux system an int is 4 bytes, so an array of five is 20 bytes.
int a[5];
printf("%zu\n", sizeof a); /* 20 on LP64 */
printf("%zu\n", sizeof a / sizeof a[0]); /* 5, the element count */
sizeof a / sizeof a[0] is the standard idiom for the element count, and it is safe because sizeof works at compile time for a real array. The division never executes at run time.
The catch is that C does no bounds checking. Accessing a[5] on an array of five is what the C standard calls a program that breaks its rules; anything may happen, from wrong data to a crash. The compiler may not even warn. You are responsible for staying inside the array.
Reading or writing past the end of an array is not an error C reports for you. It is undefined behavior, and in embedded systems the stray write often lands on a neighbouring variable, a saved return address, or a memory-mapped register. We return to this in the last section.
learner@embeddex:~/lab$ # five ints, plus a second array that only sets its first two elements
learner@embeddex:~/lab$ cat arr.c
#include <stdio.h>
int main(void)
{
int a[5] = {22, 37, 3490, 18, 95};
int b[5] = {22, 37};
printf("sizeof a = %zu\n", sizeof a);
printf("count = %zu\n", sizeof a / sizeof a[0]);
printf("a[0] = %d, a[4] = %d\n", a[0], a[4]);
printf("b[2] = %d, b[3] = %d, b[4] = %d\n", b[2], b[3], b[4]);
return 0;
}
learner@embeddex:~/lab$ # compile with warnings turned up
learner@embeddex:~/lab$ gcc -Wall -Wextra -o arr arr.c
learner@embeddex:~/lab$ # sizeof is 20 bytes, the count is computed, and partial init zero-fills
the rest
learner@embeddex:~/lab$ ./arr
sizeof a = 20
count = 5
a[0] = 22, a[4] = 95
b[2] = 0, b[3] = 0, b[4] = 0Strings and the NUL terminator
4 min readC has no real string type. A string is a char array whose final meaningful byte is the a byte with value zero that marks the end of a C string, written '\0' in code, often called NUL to distinguish it from the NULL pointer. Every text in double quotes, stored by the compiler as a constant array of char ending in a NUL byte you write, like "hello", is stored as six bytes: h e l l o \0.
A string literal is read-only. The standard says that writing to one is undefined behavior, and on real systems the compiler places literals in a read-only part of memory so a write attempt faults. This is why the two declarations below differ.
char *s = "hello"; /* pointer to a read-only literal */
char t[] = "hello"; /* a writable copy of the literal */
s points at the literal itself; s[0] = 'J'; is undefined behavior and usually crashes. t is an array that copied the literal into writable storage; t[0] = 'J'; is fine. Use a const-qualified pointer when you only need to read a literal, so the compiler catches accidental writes.
const char *s = "hello"; /* the write is now a compile error */
The length of a string is not stored anywhere. strlen from <string.h> counts bytes until it finds the NUL.
#include <string.h>
const char *s = "hello";
printf("%zu\n", strlen(s)); /* 5, not counting the NUL */
strlen returns an unsigned integer type big enough for any object size, returned by sizeof and strlen and printed with %zu. You print it with %zu. Remember that strlen is O(n): it walks the whole string every time you call it, so calling it inside a loop over the same string turns a linear pass into a quadratic one.
Going deeperWhere do string literals actually live
On a typical Linux toolchain, string literals are placed by the linker in a read-only section such as .rodata, which the kernel maps read-only, so a write to it faults. That is why writing to a literal often raises a segmentation fault rather than silently corrupting data. The compiler is also free to merge identical literals, so two occurrences of "error" in one translation unit may share one copy, and writing to one would corrupt the other. None of this is guaranteed by the standard, which only promises that the program has undefined behavior if you write. Treat literals as immutable and you are correct on every platform.
int main(void)
{
const char *s = "hello";
printf("strlen = %zu\n", strlen(s));
printf("sizeof literal = %zu\n", sizeof "hello");
char t[] = "hello";
t[0] = 74;
printf("after write = %s\n", t);
return 0;
}
learner@embeddex:~/lab$ # compile it
learner@embeddex:~/lab$ gcc -Wall -Wextra -o str str.c
learner@embeddex:~/lab$ # strlen is 5, the literal is 6 bytes, and writing to a char[] copy work
s (74 is ASCII J)
learner@embeddex:~/lab$ ./str
strlen = 5
sizeof literal = 6
after write = Jello
learner@embeddex:~/lab$ # a char * points at the read-only literal itself
learner@embeddex:~/lab$ gcc -Wall -Wextra -o crash crash.c
learner@embeddex:~/lab$ # writing through the pointer faults: literals live in read-only memory
learner@embeddex:~/lab$ ./crash
bash: 569 Segmentation fault (core dumped) ./crashArrays decay to pointers
3 min readIn almost every expression, an array name turns into a pointer to its first element. This conversion is called the automatic conversion of an array expression into a pointer to its first element. That is why a function can never really receive an array: it receives a pointer.
void print_all(int *a, int n)
{
for (int i = 0; i < n; i++)
printf("%d\n", a[i]);
}
When you write the parameter as int a[], the compiler adjusts it to int *a before you ever run the code. These three signatures are identical.
void f(int *a, int n); /* pointer, the usual form */
void f(int a[], int n); /* same thing */
void f(int a[5], int n); /* the 5 is ignored, same thing */
Because the length is lost in the decay, you must pass it separately, as n above. This is the single most important rule of the lesson: an array parameter carries no length, so carry it yourself.
You write the call: the caller names the array and its length, like
f(arr, 5).The array decays: the expression
arrconverts to a pointer toarr[0].Only the address copies: the callee receives an 8-byte pointer on LP64, not the 20 bytes of the array.
The length travels separately: the
5is an ordinary argument, nothing enforces it against the real size.The callee indexes through the pointer:
a[i]means*(a + i), stepping i elements from the pointer.
This explains a famous trap. Inside the function, sizeof a is the size of the pointer, not the array.
void bad_size(int a[100])
{
printf("%zu\n", sizeof a); /* 8 on LP64, not 400 */
}
The decay also means a function can modify the caller's array. Since the callee holds a pointer to the same memory, writes through it are visible outside.
void double_all(int *a, int n)
{
for (int i = 0; i < n; i++)
a[i] *= 2;
}
int x[5] = {1, 2, 3, 4, 5};
double_all(x, 5); /* x is now {2, 4, 6, 8, 10} */
This is the seed of the pass-by-pointer idea we build on later: a pointer gives a callee a way to reach the caller's data.
learner@embeddex:~/lab$ gcc -Wall -Wextra -o decay decay.c
decay.c: In function ‘size_in_fn’:
decay.c:4:46: warning: ‘sizeof’ on array function parameter ‘a’ will return size of ‘int *’ [-Ws
izeof-array-argument]
4 | printf("array parameter : %zu\n", sizeof a);
| ^
decay.c:2:21: note: declared here
2 | void size_in_fn(int a[100])
| ~~~~^~~~~~
decay.c: In function ‘main’:
decay.c:10:5: warning: ‘size_in_fn’ accessing 400 bytes in a region of size 20 [-Wstringop-overf
low=]
10 | size_in_fn(a);
| ^~~~~~~~~~~~~
decay.c:10:5: note: referencing argument 1 of type ‘int[100]’
decay.c:2:6: note: in a call to function ‘size_in_fn’
2 | void size_in_fn(int a[100])
| ^~~~~~~~~~
learner@embeddex:~/lab$ # 20 bytes in main, 8 bytes inside the function: the length did not trav
el
learner@embeddex:~/lab$ ./decay
main scope : 20
array parameter : 8The string and memory toolkit
5 min readEverything in this section comes from <string.h>, declared in string(3). The functions divide into two families: string functions, which operate on NUL-terminated char arrays, and memory functions, which operate on raw bytes with an explicit length.
String functions first. strlen returns the length without the NUL. strcpy(dst, src) copies src, including its NUL, into dst with no bounds check. strcat(dst, src) appends src after the existing text of dst, again with no check. strcmp(a, b) compares two strings and returns a negative value, zero, or a positive value depending on whether a sorts before, equal to, or after b. strchr(s, c) returns a pointer to the first c in s, and strrchr returns the last; both return NULL if absent. strstr(hay, needle) returns a pointer to the first occurrence of needle inside hay, or NULL.
char dst[64];
strcpy(dst, "sensor"); /* dst = "sensor\0" */
strcat(dst, "_temp"); /* dst = "sensor_temp\0" */
if (strcmp(dst, "sensor_temp") == 0)
puts("matched");
char *slash = strrchr("/dev/i2c-1", '/'); /* points at the last slash */
The memory family takes a byte count, not a NUL terminator. memcpy(dst, src, n) copies n bytes and requires that the two regions do not overlap. memmove(dst, src, n) copies n bytes even when they overlap. memset(p, v, n) sets n bytes to the byte value v. memcmp(a, b, n) compares n bytes and returns negative, zero, or positive.
char buf[16];
memset(buf, 0, sizeof buf); /* zero the whole buffer */
memcpy(buf, "id=42", 6); /* exact bytes, adds no NUL */
if (memcmp(buf, "id=", 3) == 0)
puts("starts with id=");
memcpy and memmove differ only in the overlap rule. When a shift within one buffer could move bytes forward, memcpy may corrupt the data because it may read a byte after it has been overwritten. Use memmove whenever the regions might overlap, and memcpy only when you can prove they do not.
For every lesson from here on, compile with gcc -Wall -Wextra -Werror. These flags turn the dangerous string functions into errors on some toolchains via -Werror plus the FORTIFY checks, and they catch many size mistakes before you run anything.
Two functions deserve special care. strncpy(dst, src, n) does not behave the way its name suggests. It copies at most n bytes from src, and if src is shorter it zero-pads dst out to n bytes, but if src is n bytes or longer it writes no NUL at all, leaving dst unterminated. This is a classic source of bugs. strncat(dst, src, n) is friendlier: it appends at most n bytes from src and always writes a terminating NUL.
For formatting, sprintf(buf, fmt, ...) writes into buf with no limit and is banned in modern code. snprintf(buf, size, fmt, ...) writes at most size - 1 characters plus a NUL, and returns the number of characters it would have written had the buffer been large enough. Comparing that return value against size tells you whether the result was truncated.
char line[32];
int need = snprintf(line, sizeof line, "temp=%d", value);
if (need >= (int)sizeof line)
fprintf(stderr, "output truncated\n");
The same rule applies to reading input: gets had no way to limit how many bytes it read, was removed from C11, and no longer appears in modern glibc. Replace it with fgets(buf, sizeof buf, stdin), which takes a size, or with getline where available.
Going deeperstrncpy exists for fixed-width fields, not for safe copying
strncpy was designed to fill fixed-width records in very early UNIX directory entries, where a name field was a fixed 14 bytes and shorter names had to be padded with NULs. That origin explains both quirks: it zero-pads to the full width, and it need not terminate. For ordinary bounded copying it is the wrong tool. Prefer snprintf for formatted output, or a length-tracked copy you write yourself, and reserve strncpy for the rare case where you genuinely want a NUL-padded fixed field.
learner@embeddex:~/lab$ # compile it
learner@embeddex:~/lab$ gcc -Wall -Wextra -o toolkit toolkit.c
learner@embeddex:~/lab$ # strcpy and strcat build sensor_temp; strcmp returns 0; strstr finds th
e substring
learner@embeddex:~/lab$ ./toolkit
dst = sensor_temp
strcmp = 0
found = i2c-1
learner@embeddex:~/lab$ # snprintf takes a size and reports any truncation
learner@embeddex:~/lab$ gcc -Wall -Wextra -o snprintf snprintf.c
snprintf.c: In function ‘main’:
snprintf.c:5:50: warning: ‘%d’ directive output truncated writing 5 bytes into a region of size
3 [-Wformat-truncation=]
5 | int need = snprintf(line, sizeof line, "temp=%d", 12345);
| ^~
snprintf.c:5:16: note: ‘snprintf’ output 11 bytes into a destination of size 8
5 | int need = snprintf(line, sizeof line, "temp=%d", 12345);
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
learner@embeddex:~/lab$ # temp=12 fits in 8 bytes; need=10 says the full text would have been 10
chars
learner@embeddex:~/lab$ ./snprintf
line = temp=12
need = 10 (>= 8 means truncated)Multidimensional arrays and row-major order
2 min readA multidimensional array such as int m[2][3] is an array of arrays, laid out in memory in the layout of a multidimensional array where consecutive elements of the last index sit next to each other in memory. The elements of m are stored as m[0][0], m[0][1], m[0][2], m[1][0], m[1][1], m[1][2], with the last index varying fastest.
Try the layout below:
int m[2][3] = {
{1, 2, 3},
{4, 5, 6},
};
The compiler needs every dimension except the first to know how far to jump. When you pass a multidimensional array to a function, you must write the inner sizes.
void print_2d(int a[][3], int rows) /* inner size required */
{
for (int r = 0; r < rows; r++) {
for (int c = 0; c < 3; c++)
printf("%d ", a[r][c]);
printf("\n");
}
}
The first dimension can be left empty because the compiler does not use it to compute an offset; the inner dimension sets the stride between rows. This is why an int** is not interchangeable with an int[][N].
Take the base: start from the address of the first element of the array.
Multiply the row index: skip 1 row by the row width, here 3 elements.
Add the column index: move 2 more elements within that row.
Scale by element size: multiply the total of 5 by sizeof(int) to get a byte offset.
Dereference: read the int at base plus that byte offset.
Going deeperint** is a different animal from int[][N]
A pointer-to-pointer int **pp points to a first block of pointers, each of which points to its own separately allocated row. A two-dimensional array int m[2][3] is one contiguous block with no pointer indirection. They have different memory layouts, different sizeof values, and different address arithmetic, so a function that declares int **a cannot be passed an int m[2][3]. The exact type of a pointer to a row of three ints is int (*)[3], and void f(int (*a)[3]) is the same parameter as void f(int a[][3]). When code uses int** for a matrix, the rows are usually heap-allocated individually, a pattern that returns in the heap lesson.
Pass-by-pointer patterns
3 min readIn C every argument is a copy. If you pass an int and the function changes it, the caller sees nothing. To let a callee write a result into the caller's variable you pass a pointer to that variable. The parameter that receives such a pointer is called an a pointer parameter through which a function writes a result back to the caller.
#include <math.h>
#include <stdbool.h>
bool safe_sqrt(double x, double *result)
{
if (x < 0.0)
return false;
*result = sqrt(x);
return true;
}
double r;
if (safe_sqrt(9.0, &r))
printf("%f\n", r); /* 3.000000 */
Here the function returns success or failure in its return value and writes the actual answer through result. Splitting status from data this way is a common pattern, because a return value of zero could be a valid result.
Out-parameters are also how a function returns several values at once.
void min_max(const int *a, int n, int *lo, int *hi)
{
*lo = *hi = a[0];
for (int i = 1; i < n; i++) {
if (a[i] < *lo) *lo = a[i];
if (a[i] > *hi) *hi = a[i];
}
}
int lo, hi;
min_max(a, 5, &lo, &hi);
Inside the callee, *lo means the caller's variable, so the write lands back in main. The same pointer gives a function a way to modify any caller data, as with the double_all example earlier.
In min_max the array pointer is const int *a because the function only reads it, while lo and hi are non-const because the function writes them. Marking read-only parameters const makes the direction of data flow obvious and lets the compiler catch accidental writes.
The most important out-parameter in every program is the one behind scanf and its friends: scanf("%d", &x) works because it receives the address of x. Without the &, scanf would write into a garbage location and crash or corrupt memory.
if (a[i] > *hi) *hi = a[i];
}
}
int main(void)
{
int a[5] = {42, 7, 93, 11, 58};
int lo, hi;
min_max(a, 5, &lo, &hi);
printf("min = %d, max = %d\n", lo, hi);
return 0;
}
learner@embeddex:~/lab$ # compile it
learner@embeddex:~/lab$ gcc -Wall -Wextra -o minmax minmax.c
learner@embeddex:~/lab$ # one call writes two results back through lo and hi
learner@embeddex:~/lab$ ./minmax
min = 7, max = 93
learner@embeddex:~/lab$ # scanf is the classic out-parameter: it needs &x to write the parsed va
lue
learner@embeddex:~/lab$ gcc -Wall -Wextra -o scan scan.c
learner@embeddex:~/lab$ # scanf writes 42 through the pointer; without the & it would corrupt me
mory
learner@embeddex:~/lab$ printf '42\n' | ./scan
n = 1, x = 42argv, argc and arrays of strings
2 min readA program receives its command-line arguments through main in one of two standard forms. The second form gives access to the arguments.
int main(void) { /* no arguments */ }
int main(int argc, char **argv) { /* with arguments */ }
argc is the number of arguments, and argv is an array of pointers to strings. argv[0] is the program name as it was invoked, and argv[1] through argv[argc - 1] are the arguments. The C standard guarantees that argv[argc] is a null pointer, so the array is easy to walk to its end.
#include <stdio.h>
int main(int argc, char **argv)
{
for (int i = 0; i < argc; i++)
printf("argv[%d] = %s\n", i, argv[i]);
return 0;
}
Run with ./prog alpha beta and the output is three lines: the program name, alpha, then beta. The strings themselves are separate arrays somewhere in memory; argv is an array of pointers into them. Writing char *argv[] instead of char **argv is exactly the same type as a parameter, by the decay rule from earlier.
Parsing arguments by hand gives fine control over flags and validation. A small parser reads each argument, compares it against the flags it accepts, and handles the rest as positional values.
#include <stdio.h>
#include <string.h>
int main(int argc, char **argv)
{
int verbose = 0;
for (int i = 1; i < argc; i++) {
if (strcmp(argv[i], "-v") == 0) {
verbose = 1;
} else if (argv[i][0] == '-' && argv[i][1] != '\0') {
fprintf(stderr, "unknown option: %s\n", argv[i]);
return 1;
} else {
printf("file: %s\n", argv[i]);
}
}
if (verbose)
printf("verbose mode\n");
return 0;
}
The expression argv[i][0] reads the first character of argument i: argv[i] is a char*, so argv[i][0] is a char. Note the guard argv[i][1] != '\0' so a lone - is treated as a filename rather than a flag.
Going deeperWho puts argv on the stack
On Linux, the kernel does not call main directly. It loads the program and places the argument strings, the environment strings, and an auxiliary vector (auxv) on the initial stack of the new process, then enters the C runtime entry point. The runtime, via __libc_start_main in glibc, reads that region and forwards argc, argv and envp to main. The guarantee that argv[argc] is NULL comes from the C standard, and the runtime makes it true. When you use a C library other than glibc, such as musl on a small embedded image, the mechanism is the same in outline because the standard demands the same observable interface.
Bounded and length-prefixed strings
2 min readThe NUL-terminated model has two costs: computing the length is O(n), and a missing terminator lets a read run off the end. An alternative is to carry the length explicitly. This is how many embedded protocols and files store strings, because it makes lengths O(1) and allows embedded NUL bytes, which a NUL-terminated string cannot hold.
struct sbuf {
size_t len;
char data[16];
};
A struct that stores a length and a fixed buffer records the size without a terminator. A cleaner form for a variable-size string is the a member declared with empty brackets as the last member of a struct, whose size is not counted in sizeof.
struct sbuf {
size_t len;
char data[]; /* flexible array member */
};
The flexible array member is written char data[] and must be the last member. It contributes zero to sizeof(struct sbuf), which therefore returns just the size of len plus any padding. You allocate the object with room for the header and the data together, an allocation pattern we complete in the heap lesson.
struct sbuf *s = make_sbuf(64); /* allocates sizeof(struct sbuf) + 64 bytes */
On a constrained board, walking a string with strlen repeatedly wastes CPU, and an unterminated buffer is a common cause of overruns that corrupt heap metadata or a neighbouring structure. Length-prefixed records are the norm in flash filesystems, log frames, and wire protocols such as TLV (type, length, value) encodings. When you design a small binary format, store the length rather than relying on a terminator.
The two representations trade one cost for another. A NUL-terminated string is compact and idiomatic but needs O(n) scans and discipline around the terminator. A length-prefixed string makes length O(1) and allows any byte value, at the cost of storing the length and of writing your own helpers, since the standard library string functions assume NUL termination.
Classic bugs and finding them in gdb
5 min readThis section is the payoff of the lesson: the classic bugs, their symptoms, and how a professional finds the exact corruption point in gdb. Each bug below is real and each has a diagnosis routine.
A writing more bytes into an array than it can hold, corrupting whatever follows it in memory is the master bug. The most common cause is copying a string into a buffer that is too small, usually with strcpy, sprintf, or a sizeof mistake.
char buf[8];
strcpy(buf, "temperature"); /* 12 bytes into an 8-byte buffer */
See the overflow below:
A subtle cousin is using sizeof(pointer) as if it were the array size. A common and wrong pattern is writing sizeof src inside a function that received src as a pointer.
void fill(char *dst, const char *src)
{
memcpy(dst, src, sizeof src); /* 8 bytes on LP64, not strlen+1 */
}
sizeof src is 8, so only eight bytes copy and the terminator may be lost. The fix is strlen(src) + 1 for a string, or passing the size as a parameter for raw memory.
Writing to a string literal is another recurring fault, already covered in the strings section: char *s = "x"; s[0] = 'y'; faults because the literal is read-only.
Returning a pointer to a stack local produces a a pointer to memory whose lifetime has ended, such as a stack frame that has returned.
char *bad(void)
{
char local[32] = "temp";
return local; /* the array dies when bad returns */
}
The address may still print correctly for a while, because the stack bytes are not erased, which is what makes the bug so hard to see. Any later call overwrites them. Never return the address of an automatic variable.
Use-after-scope is the same idea: keeping a pointer to a block-scope variable after its block ends.
An overflow that clobbers an adjacent variable may run fine for a hundred executions and then fail when a compiler changes the layout or a longer input arrives. When you see random corruption or a crash that moves when you rebuild, suspect an out-of-bounds write and hunt for it with gdb rather than guessing.
The debugger is the tool that finds the exact corruption point. Compile with -g, run under gdb, break just before the suspect write, and inspect the memory with print and x. This session finds a missing terminator.
gcc -g -Wall -Wextra overflow.c -o overflow
gdb ./overflow
Inside gdb, print evaluates an expression in the program's language, and x examines raw memory at an address. The @ operator makes an array slice from a pointer, and x/s prints memory as a NUL-terminated string.
(gdb) break 7
Breakpoint 1 at 0x11c0: file overflow.c, line 7.
(gdb) run
Breakpoint 1, main () at overflow.c:7
7 strcpy(buf, argv[1]);
(gdb) print sizeof buf
$1 = 8
(gdb) x/s buf
0x7fffffffe0e8: "temperature"
(gdb) x/12bx buf
0x7fffffffe0e8: 0x74 0x65 0x6d 0x70 0x65 0x72 0x61 0x74
0x7fffffffe0f0: 0x75 0x72 0x65 0x00
(gdb) print buf[0]@10
$2 = {116 't', 101 'e', 109 'm', 112 'p', 101 'e', 114 'r', 97 'a', 116 't', 117 'u', 114 'r'}
The x/12bx buf line is typical output, and yours will differ in addresses and layout. It shows the 12 bytes written past the 8-byte buffer, and the trailing 0x00 byte written just after the end. print buf[0]@10 prints the first ten characters as an artificial array, a fast way to see a slice of a string.
To confirm a fix, change the copy to a bounded call and re-run. For a string, snprintf(buf, sizeof buf, "%s", argv[1]) writes at most seven characters plus a NUL.
char buf[8];
snprintf(buf, sizeof buf, "%s", argv[1]); /* bounded, always terminated */
learner@embeddex:~/lab$ # strcpy copies argv[1] into an 8-byte buffer with no bound check
learner@embeddex:~/lab$ cat overflow.c
#include <stdio.h>
#include <string.h>
int main(int argc, char **argv)
{
char buf[8];
if (argc < 2) return 1;
strcpy(buf, argv[1]);
puts(buf);
return 0;
}
learner@embeddex:~/lab$ # compile with -g so gdb keeps line and symbol info
learner@embeddex:~/lab$ gcc -g -Wall -Wextra -o overflow overflow.c
learner@embeddex:~/lab$ # stop after strcpy and inspect: 12 bytes landed in an 8-byte buffer
learner@embeddex:~/lab$ gdb -q -batch -ex 'break 8' -ex 'run temperature' -ex 'print sizeof buf'
-ex 'x/s buf' -ex 'x/12bx buf' ./overflow
bash: gdb: command not found
learner@embeddex:~/lab$ # the fix: snprintf is bounded by sizeof buf and always terminates
learner@embeddex:~/lab$ gcc -g -Wall -Wextra -o fixed fixed.c
learner@embeddex:~/lab$ # only 7 characters survive; nothing overflows
learner@embeddex:~/lab$ ./fixed temperature
temperaTry it
1 min readOpen your lab environment and reproduce each bug from the last section, then find it in gdb. Start with the three reimplementations: write your own my_strlen, my_strcpy, and my_strcmp, and check them against the library versions with a few test strings, including the empty string. Then write the overflow program, run it with a long argument, and use break, print, x/s, and print buf[0]@10 to locate the exact corruption point. Finish by building the command-line argument parser that validates -v and echoes file names, and make it reject unknown options with a non-zero exit status. The practice pack extends these into graded exercises.
Key takeaways
- Arrays are contiguous memory with no stored length; you track the count yourself.
- sizeof(array) is the whole array only in its declaring scope; inside a function it is the pointer size.
- A C string is a char array ending in a NUL byte; string literals are read-only.
- As a function parameter, int a[] is int *a, so the length is lost and must be passed separately.
- strncpy zero-pads and may not NUL-terminate; prefer snprintf for bounded formatting.
- memcpy needs non-overlapping regions; memmove handles overlap.
- Out-parameters are pointers passed in so a callee can write results back to the caller.
- argv is an array of pointers with argv[argc] set to NULL; parse it by hand for fine control.
Reflect
- Explain to a colleague, in two sentences: declare, initialize and index one-dimensional and multidimensional arrays, and explain their row-major layout.
- Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
- What surprised you when you ran the commands yourself?
On a real board
Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.
References and further reading
- SpecificationC11 standard draft N1570 (ISO/IEC 9899:2011)
- Man pagestrlen(3) - Linux manual page
- Man pagestring(3) - Linux manual page
- Man pagesnprintf(3) - Linux manual page
- Official docsThe GNU C Library manual, string and array utilities
- Official docsDebugging with GDB, chapter 10 Examining Data
- SpecificationSEI CERT C Coding Standard, STR rules
Official documentation first. Links checked when the lesson was published.