Implement memset
Fill a block of memory with one byte value. An easy embedded C problem (Pointers), run and graded in the browser.
easy · Pointers · libc · void-pointer
Implement memset: set each of the first n bytes at dst to value converted to unsigned char, and return dst.
Small bootloaders and startup code often cannot link the C library and carry their own version.
Starter code
void *my_memset(void *dst, int value, size_t n) {
// Fill n bytes at dst with (unsigned char)value and return dst.
return dst;
}Example tests
Fill part of a string
char buf[8] = "abcdefg";
my_memset(buf + 1, 'x', 3);
printf("%s\n", buf);Expected output:
axxxefgReturns the destination
uint8_t buf[4] = { 1, 2, 3, 4 };
printf("%d %u %u %u\n", my_memset(buf, 0, 2) == buf, buf[0], buf[1], buf[2]);Expected output:
1 0 0 3Learn 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 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.
- Fix the dangling pointer · Repair a function that returns the address of a local array.
- 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.