简体   繁体   中英

Issue with pointers to memory allocation

Considering the following code block:

  Byte* b = (Byte*) var.rawBuffer();
  b += sizeof (Byte) * 9;
  WhateverType* aptr = (WhateverType*) b;
  WhateverType* anotherptr = aptr;
  for (int i = 0; i < N; i++) {
    assert(*anotherptr == aptr[i]);
    anotherptr += sizeof (WhateverType);
  }

Why do the assertion fail, sometimes? Is not scanning allocated memory using the [] operator with an index on the starting memory address equivalent to increment the pointer address by the size of the data type I am trying to read?

The problem is this line:

anotherptr += sizeof (WhateverType);

anotherptr is a WhateverType* pointer, not a Byte* pointer. When you perform arithmetic on a typed pointer, the total byte count is an even multiple of the type that the pointer is declared as.

So, in the line above, you are not telling the compiler to increment the pointer by just sizeof (WhateverType) number of bytes only, like you are expecting. You are actually telling it to increment the pointer by sizeof(WhateverType) number of elements, or in other words, by sizeof(WhateverType) * sizeof(WhateverType) number of bytes.

T *pointer = ...;
pointer += N;

Is effectively equivalent to the following:

pointer = reinterpret_cast<T*>(reinterpret_cast<byte*>(pointer) + (sizeof(T) * N));

Even the statement aptr[i] works the same way, as the expression pointer[N] is just syntax sugar for *(pointer + N) .

For what you are attempting, you need to increment your anotherptr pointer by N=1 element, not by N=sizeof(WhateverType) number of elements. So, use this instead:

anotherptr += 1;

Or simpler:

anotherptr++; // or: ++anotherptr;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM