vendredi 9 août 2019

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.

Prerequisites:

  1. Change the value stored in memory at pointer
  2. Don't use while and for loops ( they don't exist from processors point of view )
  3. Trust the user : no under-the-hood cleaning up. Memory functions should generate "droplets" that over the time result in undefined behaviour.

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
         }
    }   

The issue is this shouldn't generate an undefined behaviour as i thought it would. By this i mean, that if user doesn't use new behaviour of this function shouldn't actually alocate any memory but overwrite existing. And if i use new keyword for each element in the size , the array passed through it could result in unconnected variables in array. Therefore i would need to allocate an new array and then just swap pointers - which then needs an loop of some sorts.

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

Aucun commentaire:

Enregistrer un commentaire