Camel
Peter
Peter Campbell Smith

Memory and bells

Weekly challenge 108 — 12 April 2021

Week 108: 12 Apr 2021

Task 1

Task — Locate memory

Write a script to declare a variable or constant and print it’s location in memory.

Examples

No examples were supplied.

Analysis

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 an offset (in bytes) from some datum to the place where $x is currenly stored.

The datum is almost certainly not byte 0 of the computer's memory, so the address printed is not 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 could be relative to the start of any of these.

Script


#!/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

I completed this challenge after the closing date
and it has not been submitted to GitHub

Output


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