Fix the dangling pointer
Repair a function that returns the address of a local array. An easy embedded C problem (Pointers), run and graded in the browser.
easy · Pointers · lifetime · debugging
This function compiles, and on a real board it even appears to work until some other function reuses the stack. Run it to see what the simulator reports.
Fix it without changing the signature, so that the returned pointer stays valid for the life of the program and every call returns the same address.
Starter code
const uint8_t *default_config(void) {
uint8_t config[4] = { 0x01, 0x20, 0x00, 0x7F };
return config;
}Example tests
The data is readable after the call
const uint8_t *cfg = default_config();
printf("%02X %02X %02X %02X\n", cfg[0], cfg[1], cfg[2], cfg[3]);Expected output:
01 20 00 7FStill valid after other calls
const uint8_t *cfg = default_config();
char scratch[32];
snprintf(scratch, sizeof scratch, "%d %d %d", 1, 2, 3);
printf("%02X %02X\n", cfg[1], cfg[3]);Expected output:
20 7FLearn it first
- Pointers · Addresses, arithmetic, const, void pointers and object lifetime.
More Pointers problems
- Swap two values · Exchange two integers through pointers.
- Sum a pointer range · Walk a half-open range with a pointer.
- Pointer to the largest element · Return a pointer to the maximum of an array, or NULL when it is empty.
- Reverse a buffer in place · Reverse a byte buffer without a second buffer.
- Implement memset · Fill a block of memory with one byte value.
- Implement memcpy · Copy a block of bytes between two non-overlapping buffers.
- Implement memmove · Copy bytes correctly even when source and destination overlap.
- Advance a cursor · Move a caller's string pointer past leading whitespace.
- Generic swap · Exchange two objects of any type, byte by byte.
- Look up a record · Search an array of structs and return a pointer to the match.
- Align an address · Round an address up to a power-of-two boundary.
- From a member to its container · Recover a pointer to a struct from a pointer to one of its members.
- Index a matrix through a pointer · Read an element of a 2-D array given only a pointer to its first element.
- Fix: the display shows garbage · A formatting function returns a pointer to its own local buffer.
- Fix: the first job is sometimes wrong · A function frees a list and then reads from it.