rudicangiotti
rudicangiotti

Reputation: 566

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?

Upvotes: 0

Views: 69

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 598194

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;

Upvotes: 1

Related Questions