Self-Mutilating Program
Labyrinth, 2 bytes
>@
The >
rotates the source so that it becomes
@>
The instruction pointer is now in a dead end and turns around to hit the @
which terminates the program.
Of course, <@
would also work.
///, 1 byte
/
The program finds a /
(the start of a pattern-replacement group), and removes it in preparation to make the replacement. Then it reaches EOF, so it gives up and halts.
Python 2, 225 bytes
import sys
from ctypes import*
c=sys._getframe().f_code.co_code
i=c_int
p=POINTER
class S(Structure):_fields_=zip("r"*9+"v",(i,c_void_p,i,c_char_p,i,p(i),i,c_long,i,c_char*len(c)))
cast(id(c),p(S)).contents.v=`len([])`*len(c)
The ending source code is a string of "0"
s whose length is equal to the number of bytes in the original compiled code object.
The code finds the running code object, sys._getframe().f_code.co_code
, and creates a structure which represents python string objects. It then gets the memory that the code actually takes and replaces it with "0"*len(c)
.
When ran, the program exits with the following traceback:
XXX lineno: 7, opcode: 49
Traceback (most recent call last):
File "main.py", line 7, in <module>
cast(id(c),p(S)).contents.v=`1+1`*len(c)
SystemError: unknown opcode
This shows that the overwrite was successful and the program dies because 0
isn't a valid opcode.
I'm surprised that this is even possible in python, frame objects are read-only, I can't create new ones. The only complicated thing this does is change an immutable object (a string).