调整结构的矢量元素 - segv

时间:2013-11-05 09:16:41

标签: c++ multithreading vector struct dynamic-memory-allocation

我正在尝试调整结构的矢量元素,它会导致segv。但是当我单独为一些小结构做它时它工作得很好。我很想知道它如何为结构分配内存,其中有一个可以调整大小的向量元素。下面的注释行在第一次迭代中导致segv(type_index = 0)。

结构: -

struct thread_data {
    dbPointer_t pObj;
    dbObjId_t   objId;
    dbObjTypeId_t type;
    dbObjId_t topCellId;
    dbIteratorId_t             objsIterId;
    int precision;
    int64_t shape_objs;
    vector<vector<vector<PL_trp_header_t *> > > ps_hdrs;
    int pool;
    int num_layers;
    int to_cell_id;
};

以下是代码片段: -

thread_data *t_data[types_length];
for(int type_index=0; type_index < types_length; ++type_index) {
                t_data[type_index] = (thread_data*)malloc(sizeof(thread_data));
                t_data[type_index]->pObj = NULL;
                t_data[type_index]->objId = objId;
                t_data[type_index]->type = shape_types[type_index];
                t_data[type_index]->topCellId = topCellId;
                t_data[type_index]->objsIterId = objsIterId;
                t_data[type_index]->precision = nparams.unit_precision;
                t_data[type_index]->shape_objs = 0; 
                t_data[type_index]->ps_hdrs.resize(num_layers); //this line causes segv
                t_data[type_index]->pool = pool;
                t_data[type_index]->num_layers = num_layers;
                t_data[type_index]->to_cell_id = tocell_id;               


                for (int num = 0; num < num_layers; num++) {
                    t_data[type_index]->ps_hdrs[num].resize(index_limit);

                    for (int rows = 0; rows <  index_limit; rows++) 
                        t_data[type_index]->ps_hdrs[num][rows].resize(index_limit);
                }

                for(int i = 0; i < num_layers; i++) {
                    for (int rows = 0; rows < index_limit; rows++) {      
                        for (int cols = 0; cols < index_limit; cols++) {
                            t_data[type_index]->ps_hdrs[i][rows][cols] = alloc_hdr(pool);
                        }
                    }
                }



                printf("In main: creating thread %d \n", type_index);
                rc_thread = pthread_create(&threads[type_index], NULL, thread_fn, (void *) &t_data[type_index]);
                if (rc_thread){
                    printf("ERROR; return code from pthread_create() is %d\n", rc);
                    exit(-1);
                }
                free(t_data[type_index]);
            }

1 个答案:

答案 0 :(得分:1)

我认为您使用malloc分配数据。在这种情况下,不会调用对象和theier成员的构造函数。这适用于POD,但不适用于vector等类。在出错的行中,您尝试访问某些单位化内存,如vector。请尝试使用newdelete代替mallacfree来解决此问题。