user2894356
user2894356

Reputation: 139

Pointer: Read Access Violation - why?

I have a function which can be called in two variants. The first one works fine, but the second gives a read acccess violation.

Somehow I do not see an error. Do you see a mistake?

Thanks

void doSth(uchar *ptr, uint size, bool variant_one)
{
   uchar *buffer = new uchar[size];

   // Works
   if(variant_one) {
       for(uint i=0; i<size; i++) {
           buffer[i] = (*(ptr+1));
           ptr = ptr+2;
       }
   }
   else {
       uint16_t* ptr16 = (uint16_t*) &ptr;
       for(uint i=0; i<size; i++) {
           buffer[i] =(uchar) *(ptr16)>>4; // Gives Read Access Violation
           ptr16++;
       }
   }
}

Upvotes: 0

Views: 118

Answers (1)

eerorika
eerorika

Reputation: 238331

 uint16_t* ptr16 = (uint16_t*) &ptr;

You reinterpret ptr as a pointer to uint16_t, but no such object exists at that address. Attempting to access the non-existing object results in undefined behaviour (at least until C++20; it introduces implicit creation of trivial objects in some cases).

uint16_t* ptr16 = (uint16_t*) &ptr;
   for(uint i=0; i<size; i++) {
       buffer[i] =(uchar) *(ptr16)>>4;
       ptr16++;

Assuming uchar is 8 bits wide type, there is no way that an array of size 8 bit objects would fit size number of 16 bit objects. You overflow the array.

Edit: All of the above would apply if you had written (uint16_t*) ptr; which would have made a bit more sense even though still broken. All of the above still apply to &ptr as well except that's in addition probably not what you intended.

Upvotes: 3

Related Questions