指针:违反读访问权限-为什么?

我有一个可以在两个变体中调用的函数。 第一个可以正常工作,但是第二个可以读取访问权限。

不知何故我看不到错误。 你看到一个错误?

谢谢

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++;
       }
   }
}
评论
  • 心太冷
    心太冷 回复
     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++) {
    

    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.