Python
Inspired by the Java answer:
>>> patch = '\x312\x2D7'
>>> import ctypes;ctypes.c_int8.from_address(id(len(patch))+8).value=eval(patch)
>>> 2 + 2
5
Like Java, CPython uses the same memory location for any copy of the first few small integers (0-255 if memory serves). This goes in and directly edits that memory location via ctypes
. patch
is just an obfuscated "12-7"
, a string with len
4, which eval
's to 5.
A more obfuscated version
exec("\x66\x72\x6f\x6d\x20c\x74\x79\x70e\x73\x20\x69\x6d\x70\
\x6f\x72\x74\x20c\x5f\x69\x6e\x748\x20a\x73\x20x\x3bf\x72\x6f\
\x6d\x20\x73\x74\x72\x75c\x74\x20\x69\x6d\x70\x6f\x72\x74\x20\
ca\x6cc\x73\x69\x7ae\x20a\x73\x20x0\x3bx\x2ef\x72\x6f\x6d\x5f\
a\x64\x64\x72e\x73\x73\x28\x69\x64\x284\x29\x2bx0\x28\x27\x50\
\x50\x27\x29\x29\x2e\x76a\x6c\x75e\x3d5")
Beyond 2+2
As OP mentioned, 2+2 can be kinda boring; so here's some cleaner, multiplatform, multi-width code for wanton abuse.
from __future__ import division, print_function
import struct
import ctypes
import random
# Py 2.7 PyIntObject:
# - PyObject_HEAD
# - PyObject_HEAD_EXTRA [usually nothing unless compiled with DEBUG]
# - (Py_ssize_t) ob_refcnt
# - (_typeobject) *ob_type
# - (long) ob_ival
# two platform-sized (32/64-bit) ints (ob_refcnt and *ob_type from above)
offset = struct.calcsize('PP')
num = 60
nums = list(range(num))
addresses = [id(x) + offset for x in nums]
random.shuffle(nums)
for a, n in zip(addresses, nums):
ctypes.c_ssize_t.from_address(a).value = n
print('2 + 2 =', 2+2)
print('9 - 4 =', 9-4)
print('5 * 6 =', 5*6)
print('1 / 0 =\n', 1/0)
print('(1 + 2) + 3 = ', (1+2)+3)
print('1 + (2 + 3) = ', 1+(2+3))
print('(2 + 3) + 1 = ', (2+3)+1)
print('2 + (3 + 1) = ', 2+(3+1))
Running with Python 2.7...ignore that line at the end. Works in Windows 64-bit and Ubuntu 32-bit, the two systems I have easy access to.
$ python awful.py
2 + 2 = 24
9 - 4 = 49
5 * 6 = 55
1 / 0 = 0.76
(1 + 2) + 3 = 50
1 + (2 + 3) = 68
(2 + 3) + 1 = 50
2 + (3 + 1) = 61
Segmentation fault (core dumped)
Unsurprisingly, we can break the associative property of addition, where (a + b) + c = a + (b + c), as seen in the 1st and 2nd 1+2+3
lines, but inexplicably we also break the commutative property (where a + b = b + a; 2nd and 3rd lines). I wonder if the Python interpreter just ignores superfluous parentheses around addition expressions.
echo "2+2=5";
\$\endgroup\$