Search code examples
c++11memset

C++, recreate memset with pointers and address of operators


tl;dr; How to reproduce memset with basic c++?

I am trying to figure out how memset works , and to see if I can reproduce it within normal c++ using pointers and address.

This is what I've got so far.

    void test_memset( void * origin, uint8_t val, size_t size ){
         if( size != 1 ){
             uint8_t* new_or = (uint8_t*) origin;  // casting to uint8_t*
             *new_or ^= (*new_or & 0xff); // clearing any remaining data
             *new_or ^= val;              // assigning the val
             new_or++;                    // incrementing pointer
             test_memset_alloc( new_or, val, size-1 ); // recursion
         }
    }   

So the question : What does memset look like in basic c++?

EDIT 1:

Answered here in similar manner, and here a tad bit more verbose. Both answers are better suited than my proposition.

But i would like to see some detailed solutions, that would be able to explain a Mort (the line-of-business developer) or someone with fractuated knowledge, what is happening with more clarification than :"This is frowned upon" or "not a c++ way".


Solution

  • A basic, inefficient but correct memset implementation in C or C++ looks like this:

    typedef unsigned char byte;
    
    void* memset(void* s, int c, size_t sz) {
        byte* p = (byte*)s;
    
        while (sz--)
            *p++ = (byte)c;
        return s;
    }
    

    This uses a loop because the loop is the right tool for the job. Your insistence on avoiding loops makes no sense. "they don't exist from processors point of view" is not a valid reason to avoid them. It's not a true statement to begin with, and not even a meaningful one. Your further explanation betrays a serious lack of understanding of How Things Work™. If a loop is a black box, then everything is a black box. A function call is a black box. A cast is a black box. An if statement is a black box. An arithmetic expression like (x+y)*z is a black box. None of those is more or less transparent than a loop.