在 C 中使用带有 Python.h 的 Python 库时出现分段错误

Segmentation Fault while using Python lib in C with Python.h

这是我第一次问关于堆栈溢出的问题所以请多多包涵

我正在尝试在 c 中创建一个计算器作为项目,但是在使用 Python.h

起初我使用 eval function directly provided by the python interpreter but after reading about why eval can be dangerous I used a python lib named NumExpr as suggested here 但是当我使用那个 python 库来评估代数表达式时,我在第二次输入表达式时遇到了分段错误(它是第一次工作)

这是示例代码:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <Python.h>

void my_pause()
{
    int c;
    printf("\n  Press the enter key to continue...");
    fflush(stdout);
    while ((c = getchar()) != '\n' && c != EOF) {}
}

void main()
{
    char selec[8], temp;

    while(1)
    {
        main:

        printf("Enter here : ");
        scanf("%s" , selec);
        scanf("%c" , &temp); //this scanf is necessary as it solves the input buffer

        if(strcmp(selec,"math-exp")==0)
        {
            printf("\n\n  Please note the opreators : ");
            printf("\n    for addition '+'");
            printf("\n    for subtraction '-'");
            printf("\n    for multiplication '*'");
            printf("\n    for division '/'");
            printf("\n    for exponential power '**'");
            printf("\n    for percentage '%%'");
            printf("\n    for knowing about various functions that can be used please check documentation");

            //I had to print this using printf and not by python print itself is to solve the EOL error
            printf("\n\n  Enter the mathematical expression : ");
            Py_Initialize();
            PyRun_SimpleString("import numexpr as ne");
            PyRun_SimpleString("math_exp = input()");
            //I had to print this using printf and not by python print itself is to solve the EOL error
            printf("\n  The answer is : ");
            fflush(stdout);
            PyRun_SimpleString("print(math_exp)");
            Py_Finalize();

            my_pause();
            system("clear");
            goto main;
        }
        else if(strcmp(selec,"exit")==0)
        {
            exit(0);
        }
    }
}

这在第一次时工作得很好,但如果您第二次输入 'math-exp' 以输入另一个表达式,它将显示分段错误。我正在使用 linux mint、gcc 9.4.0、python 3.8。下面是我用来编译代码的命令:

gcc test.c -o test.bin -I"/usr/include/python3.8" -L"/usr/lib/python3.8" -lpython3.8

在此先感谢您的帮助!

多次调用 Py_Finalize 会造成内存泄漏。只需将 Py_Finalize 行移到 exit(0) 之前 这个bug在2007年就已经打开了,上个月才关闭。 https://bugs.python.org/issue1635741 已在 python 3.11.

中解决