Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Memory Addresses and Addressing

Memory Addresses and Addressing

When you write a program and declare a variable, how does the computer "find" it? Why can a 32-bit system only take 4GB of RAM?

This lecture unveils the mystery of memory addresses and helps you understand the address space - the fundamental limit that determines how much memory a computer can use.


An everyday analogy: apartment building mailboxes

Imagine an apartment building where every unit has its own mailbox labeled with a unique apartment number.

When a courier delivers a letter, they only need to know the apartment number (address) to put the letter accurately into the corresponding mailbox. The way the CPU accesses memory is almost identical to the courier delivering mail:

If apartment numbers have only 2 digits (00-99), the building can have at most 100 mailboxes. Likewise, if the address bus is only 32 bits wide, the CPU can distinguish at most 2^32 different memory cells.


The nature of memory addresses

An address is just a number

From the hardware's perspective, memory is a large row of physical cells that can store 0 and 1. Each cell stores 1 byte (8 bits), and each cell has a unique number - that number is the memory address.

The CPU reads and writes memory through the three-bus system:

  1. The CPU puts the target address on the address bus - "I want mailbox 103"
  2. The CPU issues a "read" or "write" signal on the control bus - "please give me what is inside" or "please put this in"
  3. Memory puts data on the data bus (read), or takes data off the data bus (write)

Why does each address correspond to 1 byte?

This is a design choice. Some early computers used "word addressing" (each address corresponds to 2 or 4 bytes), but modern computers almost all use byte addressing - each address corresponds to 1 byte.

The benefit: it is very natural when handling characters (each ASCII character takes 1 byte), with no extra alignment or splitting logic needed.



内存地址:  0      1      2      3      4      5      6      7

         +------+------+------+------+------+------+------+------+

内容:    | 0x48 | 0x65 | 0x6C | 0x6C | 0x6F | 0x00 | 0xFF | ... |

         +------+------+------+------+------+------+------+------+

           'H'    'e'    'l'    'l'    'o'    '\0'



一个 32 位整数 0x12345678 在内存中的存储(小端序):

地址:    0      1      2      3

         +------+------+------+------+

内容:    | 0x78 | 0x56 | 0x34 | 0x12 |

         +------+------+------+------+

          低字节在低地址——这就是「小端序」(Little Endian)


Why a 32-bit system can use at most 4GB of memory

The direct reason: the width of the address bus

A 32-bit address is a binary number made of 32 zeros or ones.

The different values 32 binary bits can represent are:

2^32 = 2 x 2 x 2 x ... (32 times) = 4,294,967,296

That is about 4GB (GigaBytes).

If each address corresponds to 1 byte, then a 32-bit address space can address a total of 4,294,967,296 bytes = 4 GB.

Derivation



1 KB  = 2^10 字节 = 1,024 字节

1 MB  = 2^20 字节 = 1,048,576 字节

1 GB  = 2^30 字节 = 1,073,741,824 字节



2^32  = 2^2 × 2^30

      = 4 × 1 GB

      = 4 GB

So 32-bit = 4GB is no coincidence, but a strict mathematical relationship between the number of address bits and the addressable space.

Analogy: the number of digits in a phone number

Suppose a city's phone numbers are 8 digits (00000000 - 99999999). What is the maximum number of distinct phone numbers this city can have?

10^8 = 100 million. If the population exceeds 100 million, 8 digits are not enough - it must be upgraded to 9 digits.

Same logic: a 32-bit address "dialed" to its limit is also 4GB. When memory demand exceeds 4GB, 32-bit systems are powerless - this is why the industry collectively migrated to 64-bit.


What 64-bit means

The theoretical limit of a 64-bit address space is:

2^64 = 18,446,744,073,709,551,616 bytes ~ 16 EB (ExaBytes)

How big is this number?

No consumer motherboard today supports this much memory. Modern 64-bit CPUs usually implement only 48 physical address lines (addressing 256 TB), and Windows 10 Home is limited to 128 GB - but for now and the foreseeable future, this is "enough".

The real significance of 64-bit is not how much memory you can plug in, but that software and operating systems no longer need to devise workarounds for insufficient address space (such as PAE - Physical Address Extension - in the 32-bit era).


Comparison of addressable space across different bit widths

Address bits Number of addressable units Addressable space Vivid analogy Representative device/system
8 bits 256 256 B The length of a text message Early microcontrollers
10 bits 1,024 1 KB One page of plain text Early EEPROM
16-bit 65,536 64 KB A short story Intel 8086, 6502
20-bit 1,048,576 1 MB A medium-thickness book Intel 8088 (IBM PC)
24-bit 16,777,216 16 MB One lossless music track Early workstations
32-bit 4,294,967,296 4 GB One HD movie Pentium, ARMv7
36 bits 68,719,476,736 64 GB All the data of a small NAS x86 PAE mode
40 bits 1,099,511,627,776 1 TB The entire capacity of a consumer SSD Early ARMv8
48 bits 281,474,976,710,656 256 TB The data volume of a medium-sized data center Modern x86-64
64-bit ~1.84 × 10^19 16 EB An astronomical number, far beyond current physical memory limits x86-64 / ARMv8 architectural limit

Note: the change from 32-bit to 64-bit is not "doubling", but jumping from 4GB to 16EB - an increase of over 4 billion times! The power of exponential growth is vividly demonstrated here.


Interactive demo: address space calculator

The program below systematically shows the addressable space for different address bit widths, and lets you intuitively feel the exponential growth through visualization.

Example

"""
Memory Address Space Calculator (runoob demo)
Function:
  1. Compute the addressable space for any address bit width
  2. Print a full comparison table from 8-bit to 64-bit
  3. Visualize exponential growth
"""

import

math

def

address_space_to_str

(

bytes_val

)

:

   

"""
    Convert a byte count to a human-readable format
    Supports: B, KB, MB, GB, TB, PB, EB
    """

   

if

bytes_val

==

0

:

       

return

"0 B"

    units

=

[

'B'

,

'KB'

,

'MB'

,

'GB'

,

'TB'

,

'PB'

,

'EB'

]

    unit_idx

=

0

    value

=

float

(

bytes_val

)

   

Step up the unit level by level, keeping the value in a reasonable range

   

while

value

=

1024

and

unit_idx

<

len

(

units

)

1

:

        value /

=

1024

        unit_idx +

=

1

   

if

unit_idx

==

0

:

       

return

f

"{int(value):,} {units[unit_idx]}"

   

elif

value

=

100

:

       

return

f

"{value:,.0f} {units[unit_idx]}"

   

elif

value

=

10

:

       

return

f

"{value:,.1f} {units[unit_idx]}"

   

else

:

       

return

f

"{value:,.2f} {units[unit_idx]}"

def

print_address_space_table

(

start_bits

=

8

,

end_bits

=

64

)

:

   

"""
    Print the address space comparison table
    :param start_bits: starting bit width
    :param end_bits: ending bit width
    """

   

print

(

"="

85

)

   

print

(

"Memory Address Space Calculator - RUNOOB computer organization"

)

   

print

(

"="

85

)

   

print

(

)

   

print

(

f

"{'Address bits':<10} {'Addressable units':>20} {'Address space':>18} {'Relative to 32-bit':>15}"

)

   

print

(

"-"

85

)

   

With 32-bit as the baseline

    baseline_32

=

2

**

32

   

Select key bit widths to display

    key_bits

=

[

8

,

10

,

12

,

14

,

16

,

18

,

20

,

24

,

28

,

30

,

32

,

36

,

40

,

44

,

48

,

52

,

56

,

60

,

64

]

   

for

bits

in

key_bits:

       

if

bits

<

start_bits

or

bits

end_bits:

           

continue

        count

=

2

** bits

        space_str

=

address_space_to_str

(

count

)

       

Compute the ratio relative to 32-bit

       

if

bits

<=

32

:

            ratio

=

count / baseline_32

            ratio_str

=

f

"1/{int(baseline_32/count)}"

if

ratio

<

1

else

"1x"

else

:

            ratio

=

count / baseline_32

           

if

ratio

=

1

_000_000_000:

                ratio_str

=

f

"{ratio/1_000_000_000:,.1f} billion times"

           

elif

ratio

=

1

_000_000:

                ratio_str

=

f

"{ratio/1_000_000:,.0f} million times"

           

elif

ratio

=

1

_000:

                ratio_str

=

f

"{ratio/1_000:,.0f} thousand times"

           

else

:

                ratio_str

=

f

"{ratio:,.0f}x"

       

print

(

f

"{bits} bits{'':<5} {count:>20,}  {space_str:>18}  {ratio_str:>15}"

)

   

print

(

"-"

85

)

   

print

(

)

def

analyze_why_4gb

(

)

:

   

"""Detailed analysis of the derivation of 32-bit = 4GB"""

   

print

(

"="

85

)

   

print

(

"Deep dive: why is 2^32 = 4 GB?"

)

   

print

(

"="

85

)

   

print

(

)

   

print

(

"Derivation steps:"

)

   

print

(

)

   

print

(

"  2^10 = 1,024                             → 1 KB"

)

   

print

(

"  2^20 = 1,024 × 1,024 = 1,048,576         → 1 MB"

)

   

print

(

"  2^30 = 1,024 × 1,024 × 1,024             → 1 GB"

)

   

print

(

" = 1,073,741,824 bytes"

)

   

print

(

)

   

print

(

"  2^32 = 2^2 × 2^30"

)

   

print

(

"       = 4 × 1,073,741,824"

)

   

print

(

" = 4,294,967,296 bytes"

)

   

print

(

" = 4 GB (to be precise, 4 GiB)"

)

   

print

(

)

   

print

(

" Note: strictly speaking"

)

   

print

(

" 4 GB (Gigabyte) = 4 x 10^9 = 4,000,000,000 bytes (decimal)"

)

   

print

(

" 4 GiB (Gibibyte) = 4 x 2^30 = 4,294,967,296 bytes (binary)"

)

   

print

(

" When people in computing say '4GB of memory' daily, they actually mean 4 GiB."

)

   

print

(

)

def

visualize_growth

(

)

:

   

"""Show exponential growth with a simple ASCII bar chart"""

   

print

(

"="

85

)

   

print

(

"Exponential growth visualization (ASCII bar chart, log scale)"

)

   

print

(

"="

85

)

   

print

(

)

    bits_list

=

[

8

,

16

,

20

,

24

,

28

,

32

,

36

,

40

,

48

,

64

]

   

Use a logarithm to compress the display range

   

for

bits

in

bits_list:

        count

=

2

** bits

        log10

=

math

.

log10

(

count

)

        bar

=

"="

int

(

log10 *

3

)

 

Each 1 log10 unit = 3 equals signs

        space_str

=

address_space_to_str

(

count

)

       

print

(

f

" {bits:>3} bits |{bar:<60} {space_str}"

)

   

print

(

)

   

print

(

" Observe: from 8-bit to 64-bit, the bar length grows steadily (because it is a log scale)"

)

   

print

(

" while the actual values explode exponentially - 32-bit to 64-bit grew over 4 billion times!"

)

   

print

(

)

def

practical_questions

(

)

:

   

"""Practical application problems"""

   

print

(

"="

85

)

   

print

(

"Practical application: compute how much memory your system can support"

)

   

print

(

"="

85

)

   

print

(

)

    questions

=

[

       

(

"Old microcontroller with an 8-bit address bus"

,

8

)

,

       

(

"6502 CPU with a 16-bit address bus"

,

16

)

,

       

(

"Laptop with a 32-bit operating system"

,

32

)

,

       

(

"32-bit server with PAE enabled (36-bit physical address)"

,

36

)

,

       

(

"Modern 64-bit home computer (48-bit physical address)"

,

48

)

,

       

(

"Theoretical limit of 64-bit architecture"

,

64

)

,

   

]

   

for

desc

,

bits

in

questions:

        space

=

2

** bits

       

print

(

f

"  {desc}:"

)

       

print

(

f

" 2^{bits} = {space:,} bytes = {address_space_to_str(space)}"

)

   

print

(

)

========== Main program ==========

if

name

==

"main"

:

    print_address_space_table

(

8

,

64

)

    analyze_why_4gb

(

)

    visualize_growth

(

)

    practical_questions

(

)

   

Extra: interactive query

   

print

(

"="

85

)

   

print

(

"Custom query"

)

   

print

(

"="

85

)

   

print

(

)

    custom_bits

=

[

1

,

4

,

8

,

16

,

32

,

64

,

128

]

   

for

bits

in

custom_bits:

        space

=

2

** bits

       

print

(

f

" {bits:>3}-bit address -> {space:,} addresses"

)

       

if

bits

=

128

:

           

print

(

f

" -> {address_space_to_str(space)} (note: this number already far exceeds the total number of atoms in the observable universe!)"

)

Interactive demo: address space calculator

Drag the slider to adjust the address bit width (1-64), render the 2n formula in real time with KaTeX, and draw the memory-cell grid with CSS Grid (fully draw all 256 cells for 8-bit and below)

8

Total number of addressable units

Memory cell grid visualization (each small cell represents 1 byte)


PAE: the "life-extension" scheme for 32-bit systems

Before 64-bit became widespread, faced with the 4GB limit, Intel designed a workaround - PAE (Physical Address Extension).

PAE extends the physical address lines from 32 bits to 36 bits, allowing a 32-bit CPU to address up to 2^36 = 64 GB of physical memory.

But there is a key limitation: each process's virtual address space is still 32-bit (4GB). A single program can still use at most 4GB of memory. PAE's benefit is letting a server run more programs simultaneously, each using its own 4GB.

PAE is only a transitional solution; the real solution is a full move to 64-bit.


Virtual address vs physical address

The "addresses" we discussed earlier mainly refer to physical addresses - the real, hardware-level numbers on the memory stick.

But in modern operating systems, the addresses your program sees are not physical addresses, but virtual addresses.

Why are virtual addresses needed?

  1. Isolation and protection: program A cannot read or write program B's memory (otherwise a crashing program could wreck the whole system).
  2. Simplified programming: every program thinks it alone occupies the entire address space (say 0 to 4GB), with no need to care which addresses other programs use.
  3. Flexible memory management: the OS can temporarily write rarely used memory to disk (swapping/paging) and read it back when needed.

Inside the CPU there is a hardware unit called the MMU (Memory Management Unit), responsible for translating virtual addresses into physical addresses in real time.



程序看到的虚拟地址 → [MMU 翻译] → 物理地址 → [地址总线] → 内存条



程序写:  *(0x08048000) = 42

         ↓

MMU 查表: 虚拟页 0x08048 → 物理页 0x1A3F0

         ↓

物理地址: 0x1A3F0000 的内存单元被写入 42

Virtual addresses are the cornerstone of modern OS stability. Without virtual addresses and the MMU, a program that reads or writes out of bounds could blue-screen the whole system - a nightmare that happened daily in the DOS era.


Memory addresses as reflected in programming

In C/C++, you can directly manipulate memory addresses (pointers). Here is an intuitive example:

Example

"""
Viewing memory addresses in Python (runoob demo)
Although Python hides low-level pointers, the id() function still lets us glimpse the concept of addresses
"""

import

sys

Memory addresses of basic types

a

=

42

b

=

42

c

=

999

d

=

999

print

(

"RUNOOB memory address exploration: Python id() demo"

)

print

(

"="

60

)

print

(

)

Python caches small integers (-5 to 256); variables with the same value point to the same address

print

(

"Small integer caching phenomenon:"

)

print

(

f

" a = 42, id(a) = {id(a)} (hex: 0x{id(a):X})"

)

print

(

f

" b = 42, id(b) = {id(b)} (hex: 0x{id(b):X})"

)

print

(

f

" a and b point to the same object: {a is b}"

)

print

(

)

print

(

"Large integers are not cached:"

)

print

(

f

" c = 999, id(c) = {id(c)} (hex: 0x{id(c):X})"

)

print

(

f

" d = 999, id(d) = {id(d)} (hex: 0x{id(d):X})"

)

print

(

f

" c and d point to the same object: {c is d} (usually False, depends on the Python implementation)"

)

print

(

)

Address of a string

text

=

"Hello RUNOOB"

print

(

f

"id of string 'Hello RUNOOB': 0x{id(text):X}"

)

Address of a list and its elements

lst

=

[

10

,

20

,

30

]

print

(

f

"\nList lst = {lst}"

)

print

(

f

" id of the list itself: 0x{id(lst):X}"

)

print

(

f

" id of lst[0]: 0x{id(lst[0]):X}"

)

print

(

f

" id of lst[1]: 0x{id(lst[1]):X}"

)

print

(

f

" id of lst[2]: 0x{id(lst[2]):X}"

)

print

(

)

print

(

"Explanation:"

)

print

(

" Although Python does not expose physical memory addresses, id() returns the object's unique identifier."

)

print

(

" In the CPython implementation, id() returns exactly the object's address in virtual memory."

)

print

(

" You can see that list elements are stored scattered (not contiguous like a C array)."

)

print

(

)

32-bit vs 64-bit reflected

print

(

"="

60

)

print

(

"Bit-width info of the Python interpreter:"

)

print

(

f

"  sys.maxsize = {sys.maxsize}"

)

print

(

f

"  2^31 - 1     = {2**31 - 1}"

)

print

(

f

"  2^63 - 1     = {2**63 - 1}"

)

print

(

)

if

sys

.

maxsize

2

**

32

:

   

print

(

f

" Your Python is 64-bit (maxsize > 2^32)"

)

else

:

   

print

(

f

" Your Python is 32-bit (maxsize <= 2^32)"

)