4

I had a very stupid typo in my code...

is.read((char*)&this->id, sizeof(this-id));

missing > character after this-

Interestingly sizeof(this - id) returned 8!

What I think is... since this is a pointer, doing subtraction on this will result in another pointer that is off by value of id which can be anything depending on the value of id.

And... on 64 bit system, pointer is usually 8 bytes!

Am I correct? or missing something?

Below is the class I have.

class IndexItem : public Serializable {
public:
  IndexItem(uint32_t id, std::streampos pos) :
    id(id),
    pos(pos)
  { }
  uint32_t id;
  std::streampos pos;
protected:
  std::ostream& Serialize(std::ostream& os) const override {
    os.write((char*)&this->id, sizeof(this->id));
    os.write((char*)&this->pos, sizeof(this->pos));
    return os;
  }

  std::istream& Deserialize(std::istream& is) override {
    is.read((char*)&this->id, sizeof(this->id));
    is.read((char*)&this->pos, sizeof(this->pos));
    return is;
  }
};
Eddie
  • 761
  • 3
  • 9
  • 22

1 Answers1

8

You are correct. You can add or subtract integral types to any pointer, resulting in another pointer and sizeof(this-id)=sizeof(this) which happens to be 8 in your system.

toth
  • 2,519
  • 1
  • 15
  • 23
  • Technically this pointer subtraction is undefined behavior but we have the saving grace that the operand of sizeof is [unevaluated and therefore this avoids undefined behavior](http://stackoverflow.com/q/28714018/1708801). – Shafik Yaghmour Jul 22 '15 at 01:51
  • @ShafikYaghmour, is it undefined even if you do not dereference the result of the subtraction? In any case, as you say since this happens inside sizeof there is no UB here. – toth Jul 22 '15 at 01:54
  • Note: Boost subtracts pointers for the SharedMemory API in order to get an offset (this - blah) or offset_ptr so they can store containers in the memory block and retrieve it with another program reading the same memory block (via offset + this). – Brandon Jul 22 '15 at 02:53