使用动态数组和删除运算符时出现python内存错误

2024-10-04 01:34:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这个代码,用来测试C++代码与原始Python代码的速度(我用指针数组来确保数据是在一个连续块中,因为向量在增长时必须复制,这需要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)

你知道我该怎么解决这个问题吗

谢谢


Tags: the代码intestforobjectstimepacket
1条回答
网友
1楼 · 发布于 2024-10-04 01:34:27

这里有一些不正确的代码

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<PacketInfo> packets(18);

将分配一个大小为18的向量,包含18个连续元素,并且由于该向量没有增长,因此也没有重新分配

看看你在代码中的注释,我认为你想写的代码是

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);
    }
}

相关问题 更多 >