简体   繁体   中英

Segmentation fault in C python extension

I'm writing a C extension module for python3.7. I have a simple structure as PyObject:

typedef struct {
    PyObject_HEAD
    double attacker;
    double victim;
    double game_hardness;
    int inflation;
} RatingSystem;

And initialiser:

static int 
RatingSystem_init(RatingSystem *self, PyObject *args, PyObject *kwargs) {
    double kek;
    static char *kwargs_list[] = {"attacker", "victim", "game_hardness", "inflation"};
    if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|$dddi", kwargs_list,
                                      &self->attacker, &self->victim,
                                      &self->game_hardness, &self->inflation)) {
        return -1;
    }

    printf("Success\n");
    return 0;
}

If I run it on Mac OS under python 3.7.3, everything works fine, but if I switch to alpine 3.10 python docker image (python:3.7-alpine), On the following initialisation:

import rating_system
rs = rating_system.RatingSystem(attacker=1000.0, victim=1000.0, game_hardness=1300.0, inflation=1)

I get Segmentation fault . Running under gdb showed the following:

Program received signal SIGSEGV, Segmentation fault.
vgetargskeywords (args=0x7f87284f0050, kwargs=0x7f87284e0a00, format=<optimized out>, format@entry=0x7f8728301000 "|$dddi", kwlist=kwlist@entry=0x7f8728303020 <kwargs_list>, p_va=p_va@entry=0x7ffeeee6e4e0,
    flags=flags@entry=2) at Python/getargs.c:1640
1640    Python/getargs.c: No such file or directory.

If I remove inflation from init, code works too, ie this code:

static int 
RatingSystem_init(RatingSystem *self, PyObject *args, PyObject *kwargs) {
    static char *kwargs_list[] = {"attacker", "victim", "game_hardness"};
    if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|$ddd", kwargs_list,
                                      &self->attacker, &self->victim,
                                      &self->game_hardness)) {
        return -1;
    }

    printf("Success\n");
    return 0;
}

Works.

Is there anything wrong with my initialisation? I tried using different types for the last argument, with no luck.

According to the docs for PyArg_ParseTupleAndKeywords , the keywords argument expects a NULL-terminated array of keyword parameter names.

Add an additional NULL element to your kwargs_list :

static char *kwargs_list[] = {"attacker", "victim", "game_hardness", NULL};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM