0

In Ruby, you can use ObjectSpace._id2ref(n) to return a reference to an object with object_id n. For example:

$ a = "foo"
$ a.object_id
70142658775260
$ ObjectSpace._id2ref(a.object_id)
"foo"

I was exploring this and wanted to know what object had object_id 4, but ObjectSpace._id2ref(4) raises the following RangeError:

RangeError: 0x00000000000004 is not id value

My understanding is that before Ruby 2.0, nil's object id was fixed at 4, but in Ruby 2.0 nil has object id 8. There's an explanation for this here.

Is the error raised simply because no object has 4 as a fixed object id? If so, is it possible for some object foo to happen to be assigned object_id 4 at runtime?

mose
  • 40
  • 1
  • 7

1 Answers1

1

Yes, you are correct, in 2.0 and after, there will be no object with id 4, and it is not possible to create one with that id.

Excluding the special builtin types (nil, false, true, Symbols, and numbers), an object's id is taken from its memory address, and assuming a 32 bit machine, the address needs to have a 4 byte alignment, which means that the last 2 bits of the address will be 0.

If that is the case, then the id 4 would theoretically still be a valid address for an object, and hence a valid id, but that object would live in an invalid memory address, since it would most likely already being used by the program itself to run in its virtual address space.

Silver Phoenix
  • 522
  • 1
  • 5
  • 10