</>EmbeddedInterview
← All problems · Pointers & Strings

Fill a Memory Region with a Byte

Easy

Implement memset semantics without calling libc. Assume n bytes are writable when n is nonzero. Implement void *fill(void *p, int value, size_t n).

Choose C or C++ and write your code on the right and press Run (or Ctrl + Enter). Hidden tests check your functions and print the result below the editor.

Use unsigned char for byte access.

#include <stdio.h>
#include <stdint.h>
#include <stddef.h>
#include <string.h>

void *fill(void *p, int value, size_t n)
{
    unsigned char *b=p; for(size_t i=0;i<n;++i)b[i]=(unsigned char)value; return p;
}

Convert the value to a byte and write exactly n bytes.

solution.c
OutputPress Run to compile and test your code.
Show the hidden tests
/* ---- tests ---- */
static int fails;
#define CHECK(c) do { if (!(c)) { printf("FAIL line %d: %s\n", __LINE__, #c); fails++; } } while (0)
int main(void)
{
    unsigned char a[4]={0,0,0,9};
    CHECK(fill(a,0x1ab,3)==a);
    CHECK(a[0]==0xab && a[2]==0xab && a[3]==9);
    CHECK(fill(a,0,0)==a && a[0]==0xab);
    puts(fails ? "Some tests failed" : "All tests passed");
    return fails != 0;
}