Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I cause or create an invalid memory reference in Python on purpose?

Tags:

python

How do I cause or create an invalid memory reference in Python on purpose?

This is a bit of a bar-bet. I'm told it can't be done. I don't believe that.

like image 613
jcolebrand Avatar asked Feb 05 '26 08:02

jcolebrand


2 Answers

>>> import ctypes
>>> p = ctypes.POINTER(ctypes.c_int)(ctypes.c_int())
>>> p[100000000]
Segmentation fault
like image 96
Sven Marnach Avatar answered Feb 07 '26 20:02

Sven Marnach


Create a module in C:

#include <Python.h>

static PyMethodDef SpamMethods[] =
{
    {NULL, NULL, 0, NULL}
};

PyMODINIT_FUNC
initspam(void)
{
    (void)Py_InitModule("spam", SpamMethods);
    int* invalidptr = NULL;
    *invalidptr = 42;
}

And then from python:

import spam
like image 38
Chris Eberle Avatar answered Feb 07 '26 21:02

Chris Eberle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!