PyRun_SimpleString调用会导致内存损坏
PyRun_SimpleString call cause memory corruption?
我正在尝试在C++中使用Python并具有以下代码。我打算在用户输入路径上解析和执行sys.path.append。看起来对PyRun_SimpleString的调用导致了某种溢出到该类的私有类 var 中。这是怎么发生的?我尝试了各种缓冲区大小 50、150、200,它没有改变输出。
class Myclass
{
...
private:
char *_modName;
char *_modDir;
};
Myclass::Myclass()
{
Py_Initialize();
PyRun_SimpleString("import sys");
PyRun_SimpleString((char *)"sys.path.append('/home/userA/Python')");
}
Myclass::init()
{
// this function is called before Myclass::test()
// a couple other python funcitons are called as listed below.
// PyString_FromString, PyImport_Import, PyObject_GetAttrString, PyTuple_New, PyTuple_SetItem, PyObject_CallObject, PyDict_GetItemString
}
Myclass::test()
{
char buffer[150];
char *strP1 = (char *)"sys.path.append('";
char *strP2 = (char *)"')";
strcpy (buffer, strP1);
strcat (buffer, _modDir);
strcat (buffer, strP2);
printf("Before %sn", _modDir);
printf("Before %sn", _modName);
PyRun_SimpleString(buffer);
printf("After %sn", _modName);
}
这是输出。仅供参考,我使用 a,b,c,d,f 仅用于说明目的。它几乎像PyRun_SimpleString(缓冲区)一样填充缓冲区的末端_modName。
Before /aaa/bbb/ccc/ddd
Before ffffff
After cc/ddd'
感谢Klamer Schutte在正确的方向上暗示。我的代码中的 DECRF 是罪魁祸首。我猜,对参考的工作原理不熟悉。DECREF调用发布了pValue以及_modName指向的内容。一个更初学者的问题,我应该在_modName作业后添加一个Py_INCREF(pValue)吗?
_modName = PyString_AsString (PyDict_GetItemString(pValue, (char*)"modName"));
Py_DECREF(pValue);
相关文章:
- 如何针对特定情况调试和修复此双自由内存损坏问题
- 正在调试 malloc():新内存损坏
- 仅特定内核计数上的 MPI 内存损坏
- C++程序错误:malloc():内存损坏
- 调用std::函数成员时内存损坏
- C++ 内存损坏检测
- 由于标头中的 #define 不匹配而导致内存损坏
- C STD ::线程中的种族状况或内存损坏
- malloc()内存损坏仅通过为特定数量编写int数组
- 字符串标记化期间的内存损坏
- 从检测到 glibc 正常退出 - malloc():内存损坏
- 放置在外部 DLL 中的类中的字符串数据的内存损坏
- std :: string ::擦除会导致内存损坏
- 编译器如何检测内存损坏
- mix_playMusic导致内存损坏
- 在使用新操作员和C 中的结构的调用构造函数时,获得内存损坏(Malloc)
- 两个内联程序集调用与一个内联程序集调用中的内存损坏?
- 如何调试不确定内存损坏?
- 增强Dijkstra代码会导致片段内存损坏
- 内存损坏从vb.net调用c dll