0

我正在尝试调整结构的向量元素的大小,它会导致 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]);
            }
4

1 回答 1

1

我认为您正在使用malloc. 在这种情况下,不会调用对象及其成员的构造函数。这适用于 POD,但不适用于vector. 根据错误,您尝试访问一些未初始化的内存,例如vector. 尝试newanddelete代替mallacandfree来解决这个问题。

于 2013-11-05T09:35:12.817 回答