Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby How we can unfreeze the string using pointer

Tags:

pointers

ruby

mri

I was going through a blog and found following code snippet:

require 'fiddle'
str = 'water'.freeze
str.frozen? # true

memory_address = str.object_id * 2
Fiddle::Pointer.new(memory_address)[1] &= ~8
str.frozen? # false

Can anyone explain, I couldn't understand how following line is actually unfreeze the string.

Fiddle::Pointer.new(memory_address)[1] &= ~8
like image 602
Hardik Avatar asked Sep 25 '26 22:09

Hardik


1 Answers

MRI heap stores RValue struct at that address, first field of that is flags, which has bit FL_FREEZE indicating if the object is frozen - 11th bit in an integer, in x86 bytes go in reverse order, so it can be accessed as 3rd bit of second byte.

The code sets that bit to zero thus 'unfreezing' the object

like image 183
Vasfed Avatar answered Sep 28 '26 21:09

Vasfed



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!