我有这段代码用于测试 C++ 代码与原始 python 代码的速度(我使用指针数组来确保数据位于单个连续 block 中,并且因为 vector 必须在它会增长,这需要 O(N) 时间):
void MyClass::test_packet(){
time_t t1;
time(&t1);
PacketInfo* packets;
for(int i = 0; i < 336000; i++){
for(int j = 0; j < 18; j++){
int N = 18;
// allocate memory for 18 objects in a continous block
packets = new PacketInfo[N];
// create the packetInfo objects
packets[i] = PacketInfo(i, i);
// free the 18 memory blocks
delete[] packets;
}
}
time_t t2;
time(&t2);
cout << "total time for 336000 * 18 packets : " << (t2 - t1) << "seconds" << endl;
}
BOOST_PYTHON_MODULE(MyClass)
{
class_<MyClass>("MyClass", init< /*parameter types go here */>())
// some other functions
.def("test", &MyClass::test_packet);
}
python 测试文件如下所示:from MyClass import *
MyClass.test()
这给了我一个双重空闲或损坏的内存错误:*** Error in `python3': double free or corruption (!prev): 0x00000000016b1b10 ***
我评论了 delete[] 运算符,但这给了我一个段错误:Erreur de segmentation (core dumped)
知道如何解决这个问题吗?谢谢
最佳答案
这里有一些不正确的代码
for(int i = 0; i < 336000; i++){
for(int j = 0; j < 18; j++){
int N = 18;
// allocate memory for 18 objects in a continous block
packets = new PacketInfo[N];
// create the packetInfo objects
packets[i] = PacketInfo(i, i);
如果 i
大于 18(显然会是)然后 packets[i]
将是越界数组访问。packets[j]
的替代方案没有多大意义,因为分配相对于循环的位置不正确(大概它应该在循环之前)。再加上你关于 vector 的陈述是不正确的。
vector<PacketInfo> packets(18);
将分配一个大小为 18 的 vector ,其中包含 18 个连续元素,并且由于 vector 没有增长,因此也没有重新分配。查看您在代码中的评论,我认为您要编写的代码是
for(int i = 0; i < 336000; i++){
int N = 18;
// allocate memory for 18 objects in a continous block
vector<PacketInfo> packets(N);
for(int j = 0; j < N; j++){
// create the packetInfo objects
packets[i] = PacketInfo(i, i);
}
}
关于python - 动态数组和删除运算符的 boost::python 内存错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62839896/