knktc's Notes

python, cloud, linux...

0%

C Code for Reproducing a Segmentation Fault

I do not really write C, but sometimes I need to use software written in C.

For example, one recent test required Python to call into a shared library through ctypes. During testing, I found that a segmentation fault would sometimes occur, and once it did, the Python process crashed as well.

This kind of crash cannot be caught with a normal Python try block. Once it happens, the interpreter simply dies. Since the original crash in my real code was random and hard to reproduce, I looked up some basic examples and wrote a tiny test library that would always crash, so I could use it to evaluate possible workarounds.

Here is the C code:

1
2
3
4
5
int fault(void)
{
char *s = "hello world";
*s = 'H';
}

Save it as segfault.c, then compile it into a shared object:

1
gcc -fPIC -shared -o ./segfault.so segfault.c

Then call it from Python with ctypes:

1
2
3
4
import ctypes

lib = ctypes.cdll.LoadLibrary('./segfault.so')
lib.fault()

Running the Python script produces:

Segmentation fault

After testing, I did not find any particularly elegant way to keep the Python interpreter itself alive after this kind of crash. In the end, I used subprocess to call a separate Python process, so the main program would survive even if the child process crashed.

If anyone has a better solution, I would genuinely love to hear it.

如果我的文字帮到了您,那么可不可以请我喝罐可乐?