这是我第一次问关于堆栈溢出的问题,所以请容忍我。
我正在尝试作为一个项目在c中创建一个计算器,但是当第二次使用Python.h在c内使用Python.h计算一个代数表达式时,我得到了一个分段错误。
起初,我使用的是python解释器直接提供的eval函数,但是在阅读了关于为什么伊娃会很危险的文章之后,我使用了一个名为NumExpr的python,如建议的这里,但是当我使用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’来输入另一个表达式,它将显示分段错误。我正在使用linux,gcc 9.4.0,python3.8。下面是我用来编译代码的命令:
gcc test.c -o test.bin -I"/usr/include/python3.8“-L/usr/lib/python3.8”-lpython3.8
提前感谢您的帮助!
发布于 2022-05-15 04:20:56
多次调用Py_Finalize
会导致内存泄漏。只需在Py_Finalize
之前移动您的exit(0)
行,此bug已于2007年打开,并于上个月关闭。https://bugs.python.org/issue1635741在python3.11中解决。
https://stackoverflow.com/questions/72248050
复制相似问题