Skip to content
BetterDL

Self-modifying code

Also called: self modifying code, self-modifying program

A program that changes its own instructions while it runs, possible because instructions are ordinary words in the same memory as data.

In a stored program computer, instructions are just words in memory, and STORE can write any word. So a program can overwrite one of its own instructions before the PC reaches it. That's self-modifying code.

When the PC gets to the changed word, the CPU fetches the new value and runs it. The CPU has no idea the word was changed; it just executes whatever is there.

Early computers used this on purpose, for example to step an address field through an array. Today it's mostly avoided: it makes programs hard to understand and debug, and modern CPUs with separate instruction caches have to do extra work to notice the change.

For tracing, the lesson is simple: always use the current contents of memory, not the original listing, when the PC reaches a word that an earlier STORE wrote to.

Worked example

Example

A program that rewrites itself

Tiny8 memory: 0: LOAD E (1E), 1: STORE 3 (23), 2: LOAD F (1F), 3: HALT (00), 4: HALT (00), E: 3F, F: 02.

  1. 1.

    LOAD E: ACC = 3F.

  2. 2.

    STORE 3: M[3] = 3F. Address 3 no longer holds HALT; it now holds ADD F.

  3. 3.

    LOAD F: ACC = 2.

  4. 4.

    Address 3 is now ADD F: ACC = 2 + 2 = 4.

  5. 5.

    Address 4: HALT. The program stops with ACC = 4. Read from the listing, you'd have stopped at address 3 with ACC = 2.

Common mistakes

  • Tracing from the original listing after a STORE has overwritten an instruction.

  • Thinking the CPU can tell code from data and will refuse to run a stored value.

Practice Self-modifying code

Interactive questions with instant feedback and a worked solution for every wrong answer.

Learn it step by step

Self-modifying code is taught in Basic CPU / Computer Architecture.