Peter’s solutions: week 108 — 12 April 2021
THE WEEKLY CHALLENGE
Memory and bells
Write a script to declare a variable or constant and print its location in memory.
I presume that what is required is the hexadecimal number
which is generated if I print a reference, for example
say \$x. That prints, for example SCALAR(0x1278260),
and one could reasonably assume that the hex value
printed is the offset (in bytes) from some datum to the
place where the value of $x is currently stored.
The datum is probably not byte 0 of the computer's physical memory, so the address printed may not be an absolute address. Linux has a - rather opaque - memory management layer that will have allocated one or more blocks of memory to me, and within that, my instance of Perl has a subset of that, and Perl itself will have a block of memory allocated to variables. The address printed might be relative to the start of any of these.
#!/usr/bin/perl # Blog: http://ccgi.campbellsmiths.force9.co.uk/challenge use v5.26; # The Weekly Challenge - 2021-04-12 use utf8; # Week 108 - task 1 - Locate memory use warnings; # Peter Campbell Smith binmode STDOUT, ':utf8'; use Encode; locate_memory(); sub locate_memory { my ($x); \$x =~ m|\((.*)\)|; say qq[\nOutput: Address of \$x is: $1]; \2 =~ m|\((.*)\)|; say qq[ Address of 2 is: $1 These are probably addresses relative to the start of the block of memory that Linux and Perl have used to store variables and constants.]; }
9 lines of code
Completed after the closing date and not submitted to GitHub
Output: Address of $x is: 0xf8d338
Address of 2 is: 0xff1bf8
These are probably addresses relative to the start
of the block of memory that Linux and Perl have
used to store variables and constants.
Any content of this website which has been created by Peter Campbell Smith is in the public domain