Search code examples
cpointersmemorymemsetpointer-arithmetic

create my own memset function in c


here is the prototype:

void *memset(void *s, int c, size_t n)

first im not sure if I have to return something because when I use the memset i do for example

memset(str, 'a', 5);

instead of

str = memset(str, 'a', 5);

here is where I am with my code:

void *my_memset(void *b, int c, int len)
{
    int i;

    i = 0;
    while(b && len > 0)
    {
        b = c;
        b++;
        len--;
    }
    return(b);
}

int main()
{
    char *str;

    str = strdup("hello");
    my_memset(str, 'a', 5);
    printf("%s\n", str);
}

I dont want to use array in this function, to better understand pointer and memory, so I dont get 2 things: - how to copy the int c into a character on my void b pointer - what condition to use on my while to be sure it stop before a '\0' char

edit: i was wondering is there a way to do this function without casting ?


Solution

  • how to copy the int c into a character on my void b pointer

    You convert the void pointer to an unsigned char pointer:

    void  *my_memset(void *b, int c, int len)
    {
      int           i;
      unsigned char *p = b;
      i = 0;
      while(len > 0)
        {
          *p = c;
          p++;
          len--;
        }
      return(b);
    }
    

    what condition to use on my while to be sure it stop before a '\0' char

    memset have to trust the length that is passed in. memset needs to work on a general piece of memory, not just a 0 terminated string - so there should not be such a check.

    If you anyway would need to check for a 0 byte. you'd do

    if (*p == 0) //or if(!*p )
         break;