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

Why can programs and data reside in the same memory

Why can programs and data reside in the same memory

In the previous lesson we saw the full picture of the von Neumann architecture—the five major components and the three buses.

In this lesson, we focus on its most revolutionary idea: treating program instructions as a special kind of data and storing them in the same memory as the data.


An everyday analogy: sheet music and a music player

Imagine two different musical devices:

Device A: a music box

A wind-up music box with a metal cylinder covered in bumps inside. Each bump plucks a steel tine to produce a note.

Want to change the tune? You have to open the music box and swap in another cylinder with a different arrangement of bumps. The cylinder itself is a physical fusion of the "program" and the "player".

Device B: a music app on a smartphone

Your phone stores hundreds of MP3 files. Tap one and it plays that one.

The MP3 files (program/data) and the player app (executor) are separate—changing a song only requires changing a file, not the phone.

The music box is a computer before von Neumann: the program is bound to the hardware, and changing the task means changing the machine.

The smartphone is a computer after von Neumann: the program is replaceable content in memory, and the hardware is a general-purpose execution platform.

Comparison Dimensions Music box (external program control) Smartphone (stored program)
How the program is stored Hardwired into the mechanical structure Stored in memory as data
Changing the track Open the machine and swap the cylinder Just tap the screen
Whether the hardware is general-purpose One music box = one tune One phone = unlimited tunes
Flexibility Almost zero Extremely high

What von Neumann did was exactly this one thing: pull the "sheet music" out of the hardware and turn it into a freely replaceable "data file". From then on, hardware is hardware and software is software.


Historical background: from "external program control" to "stored program"

2.1 Computers before von Neumann

In the early 1940s, some electronic computers were already in use, but they shared a common problem:

ENIAC (1946)—the world's first general-purpose electronic computer, with astonishing computing speed, but every time the computing task changed, engineers needed to spend days manually plugging and unplugging hundreds of cables and setting thousands of switches to "reprogram" it.

Harvard Mark I (1944)—used punched paper tape to input programs, but the program memory (the tape reader) and the data memory were two physically separate devices, so the CPU could not access program instructions the way it accessed data.

The common drawbacks of these machines:

2.2 von Neumann's breakthrough

In 1945, von Neumann proposed a bold idea in the "First Draft of a Report on the EDVAC":

Encode program instructions as binary numbers and store them together with data in the same addressable memory.

This idea brought three decisive advantages:

  1. Unified hardware: the CPU does not need to know whether a memory location holds an instruction or data—it simply reads and writes by address. This greatly simplifies hardware design.
  2. Software exists independently: the program becomes a "file" that can be stored, copied, and transmitted. This is the birth of the concept of "software".
  3. Programs can modify themselves: a program can modify its own instructions or those of other programs just as it manipulates data. This laid the foundation for epoch-making technologies such as assemblers, compilers, and operating systems.

Principle in detail: the coexistence of instructions and data in memory

3.1 Memory-module diagram: which is an instruction? which is data?

The diagram below shows a snapshot of a memory region. Each cell is a storage unit with a unique address number.

Observe—instructions and data are physically identical, all just 0s and 1s. The only way to tell them apart is who accessed it and when.

Main memory (RAM) Address Stored content Type Actual meaning 0x0000 10110001 00000101 [ Instruction ] LOAD A, 5 0x0001 00000000 00000101 [ Data ] Immediate value 5 0x0002 10110010 00000011 [ Instruction ] LOAD B, 3 0x0003 00000000 00000011 [ Data ] Immediate value 3 0x0004 00100000 00000001 [ Instruction ] ADD A, B 0x0005 00110000 01100100 [ Instruction ] STORE 100 0x0064 00000000 00001000 [ Data ] Computation result: 8 Legend: Blue highlight = instruction cell (opcode + operand) Orange highlight = data cells (immediate values, variable values, computation results) Note: instructions and data are physically identical in storage - both are binary bits; only the PC pointer when the CPU fetches an instruction decides whether it is an instruction or data.

3.2 Key question: how does the CPU distinguish instructions from data?

From the diagram above we can see a key fact: at the physical storage level, instructions and data are completely indistinguishable - both are strings of binary bits.

So how does the CPU know whether to treat a memory cell as an instruction or as data?

The answer is simple: it depends on the timing of the access and on who is accessing.

In one sentence: the same memory address is an 'instruction' when the PC points to it, and 'data' when an operand address points to it. This is the essence of the 'stored program' concept - instructions and data are physically indistinguishable and are distinguished logically by the access context.


Interactive demo: explore instructions and data in memory yourself

The Python code below creates a memory system you can explore interactively - you can write instructions or data, then inspect the content at any address in memory and decide whether it is an instruction or data.

Example

"""
Demo of mixed storage of instructions and data in memory (runoob demo)
Demonstrating the 'stored program' idea: instructions and data in the same memory block cannot be distinguished by their stored content
"""

class

MemoryInspector:

   

"""Memory Inspector - visually shows instructions and data coexisting in memory"""

   

def

init

(

self

,

size

=

256

)

:

       

Initialize memory: each cell stores an integer value (simulating 8 bits)

       

self

.

memory

=

[

0

]

       

Tag array: records the type of each address - 'instruction' or 'data'

       

Note: real hardware has no such tag! This is only for the convenience of the demo

       

self

.

type_tags

=

[

'empty'

]

       

Records a mnemonic explanation for each address (also for the convenience of the demo)

       

self

.

annotations

=

[

''

]

   

def

write_instruction

(

self

,

address

,

opcode

,

operand

,

annotation

=

""

)

:

       

"""Write an instruction into memory (occupies two cells: opcode + operand)"""

       

self

.

memory

[

address

]

=

opcode

       

self

.

type_tags

[

address

]

=

'instruction'

       

self

.

annotations

[

address

]

=

annotation

       

self

.

memory

[

address +

1

]

=

operand

       

self

.

type_tags

[

address +

1

]

=

'instruction'

       

self

.

annotations

[

address +

1

]

=

f

" Operand: {operand}"

   

def

write_data

(

self

,

address

,

value

,

annotation

=

""

)

:

       

"""Write one data cell into memory"""

       

self

.

memory

[

address

]

=

value

       

self

.

type_tags

[

address

]

=

'data'

       

self

.

annotations

[

address

]

=

annotation

   

def

inspect

(

self

,

start

=

0

,

end

=

16

)

:

       

"""View the memory content of a specified range"""

       

print

(

"="

68

)

       

print

(

f

"{'Address':>6} | {'Stored Value':>8} | {'Binary':>10} | {'Type':>12} | Meaning"

)

       

print

(

"-"

68

)

       

for

addr

in

range

(

start

,

min

(

end

,

len

(

self

.

memory

)

)

)

:

            val

=

self

.

memory

[

addr

]

            binary

=

format

(

val

,

'08b'

)

 

8-bit binary representation

            tag

=

self

.

type_tags

[

addr

]

            anno

=

self

.

annotations

[

addr

]

           

Use tags to distinguish display colors (no colors in the terminal, symbols used instead)

            marker

=

"[I]"

if

tag

==

'instruction'

else

\

                     

"[D]"

if

tag

==

'data'

else

\

                     

"[ ]"

           

if

val

!=

0

or

tag

!=

'empty'

:

               

print

(

f

"  {addr:4d} | {marker} {val:5d} |  {binary}  | {tag:>12} | {anno}"

)

       

print

(

"="

68

)

       

print

(

"[I] = Instruction [D] = Data [ ] = Free\n"

)

   

def

compare_bytes

(

self

,

addr1

,

addr2

)

:

       

"""
        Compare the raw bytes of two addresses - you will find they cannot be distinguished in binary
        """

        v1

=

self

.

memory

[

addr1

]

        v2

=

self

.

memory

[

addr2

]

        b1

=

format

(

v1

,

'08b'

)

        b2

=

format

(

v2

,

'08b'

)

       

print

(

f

"\n--- Compare address {addr1} and address {addr2} ---"

)

       

print

(

f

"Address {addr1}: binary {b1} (type: {self.type_tags[addr1]})"

)

       

print

(

f

"Address {addr2}: binary {b2} (type: {self.type_tags[addr2]})"

)

       

if

b1

==

b2

and

self

.

type_tags

[

addr1

]

!=

self

.

type_tags

[

addr2

]

:

           

print

(

f

">>> Key finding: the binary content of these two addresses is exactly the same ({b1})!"

)

           

print

(

f

">>> But their types differ: address {addr1} is {self.type_tags[addr1]},"

)

           

print

(

f

">>> address {addr2} is {self.type_tags[addr2]}."

)

           

print

(

f

">>> This shows - based on binary content alone, instructions and data cannot be distinguished!"

)

       

else

:

           

print

(

f

"The content of these two addresses is different."

)

   

def

simulate_instruction_data_ambiguity

(

self

,

addr

)

:

       

"""
        Demonstrate how the same binary value is interpreted with different meanings in different contexts
        """

        val

=

self

.

memory

[

addr

]

        binary

=

format

(

val

,

'08b'

)

       

print

(

f

"\n--- Ambiguity demo for address {addr} ---"

)

       

print

(

f

"Stored binary value: {binary} (decimal: {val})"

)

       

print

(

f

""

)

       

print

(

f

"If the CPU's PC points here (instruction fetch stage):"

)

       

print

(

f

" -> This byte is interpreted as an 'instruction opcode'"

)

       

print

(

f

" -> For example {binary} might represent the 'LOAD' instruction"

)

       

print

(

f

""

)

       

print

(

f

"If the ALU references here via an operand address (execution stage):"

)

       

print

(

f

" -> This byte is interpreted as 'data'"

)

       

print

(

f

" -> For example the decimal value {val} is just an ordinary number"

)

       

print

(

f

""

)

       

print

(

f

"The same bit sequence, read in different roles, has completely different meanings!"

)

================================================================

Demo 1: build mixed storage in memory

================================================================

print

(

">>> Demo 1: store instructions and data mixed in memory\n"

)

mem

=

MemoryInspector

(

)

Write the instruction sequence

mem.

write_instruction

(

0

,

0xB1

,

5

,

"LOAD A, 5"

)

mem.

write_instruction

(

2

,

0xB2

,

3

,

"LOAD B, 3"

)

mem.

write_instruction

(

4

,

0x20

,

1

,

"ADD A, B"

)

mem.

write_instruction

(

6

,

0x30

,

100

,

"STORE 100"

)

Write the data

mem.

write_data

(

100

,

8

,

"Computation result: 5 + 3 = 8"

)

View the full memory picture

mem.

inspect

(

0

,

8

)

mem.

inspect

(

100

,

102

)

================================================================

Demo 2: instruction/data ambiguity of the same value

================================================================

print

(

">>> Demo 2: the same binary value may be an instruction or may be data\n"

)

Deliberately write the value 5 at an address (instruction area) and also write 5 at address 200 (data area)

mem.

write_instruction

(

10

,

5

,

0

,

"This 5 is an opcode"

)

mem.

write_data

(

200

,

5

,

"This 5 is a data value"

)

mem.

compare_bytes

(

10

,

200

)

Ambiguity demo

mem.

simulate_instruction_data_ambiguity

(

10

)

================================================================

Demo 3: the concept of self-modifying code (advanced topic)

================================================================

print

(

">>> Demo 3: the concept of a program modifying itself\n"

)

print

(

"Because instructions and data are in the same memory, a program can modify its own instructions!"

)

print

(

"This is exactly the capability brought by the stored-program architecture."

)

print

(

""

)

print

(

"For example, a program can change the instruction STORE 100 at address 6 into STORE 200:"

)

print

(

f

"Before modification address 6: {mem.memory[6]} (opcode)"

)

print

(

f

"Before modification address 7: {mem.memory[7]} (operand)"

)

The program modifies itself: change the operand of STORE from 100 to 200

mem.

memory

[

7

]

=

200

mem.

type_tags

[

7

]

=

'data'

mem.

annotations

[

7

]

=

"Modified by the program itself: operand 100 -> 200"

print

(

f

"After modification address 7: {mem.memory[7]} (operand changed)"

)

print

(

""

)

mem.

inspect

(

6

,

8

)

print

(

">>> This capability is the foundation of technologies such as compilers, dynamic linkers, and virtual machines."

)

Run this program and you will clearly see: instructions and data are simply different 'roles' within the same block of memory. They share the same storage and addressing mechanisms - this is the most central ingenuity of the Von Neumann architecture.

3.3 Interactive demo: click a memory cell to view its content (runoob)

Below is a simulation of a 64-byte memory region. Blue cells represent instructions, orange cells represent data, and gray cells are free areas. Hover over any cell to see its stored raw value,Click a cellView the detailed description - including whether the address actually stores an 'instruction' or 'data', and its real meaning.

Instruction

Data

Empty

Click a memory cell above to view the type and meaning of the content stored at that address


Comparison with the Harvard architecture

The Von Neumann architecture is not the only computer architecture. Its main 'competitor' isHarvard Architecture.

Comparison Dimensions von Neumann architecture Harvard architecture
Memory A single memory, with instructions and data sharing it Two separate memories, with instructions and data kept apart
Bus One set of address/data buses, with instructions and data time-multiplexed Two independent sets of buses, allowing simultaneous access to instructions and data
Advantages Simple hardware design, high memory utilization, flexible software Can fetch instructions and data simultaneously, faster (pipeline-friendly)
Disadvantages Instruction fetch and data fetch may conflict (Von Neumann bottleneck) More complex hardware, instruction storage and data storage cannot be allocated dynamically
Typical application General-purpose computers such as PCs and servers Embedded MCUs, DSP digital signal processors

Modern CPUs often blend the two architectures in actual implementations: externally they present the unified memory model of the Von Neumann architecture (easy to program), while internally at the L1 Cache level they use separate instruction and data caches (borrowing the speed advantage of the Harvard architecture). This is the so-called 'Modified Harvard Architecture'.