在循环中释放malloc后的内存



我在循环中分配了一些内存-当我完成tr_data变量时如何释放它?(我对c++相当陌生)

    #define Malloc(type,n) (type *)malloc((n)*sizeof(type))
    struct svm_problem tr_data;
    tr_data.l = (int) prm_num_samples_anchored.array[bar];
    tr_data.y = Malloc(double, tr_data.l);
    tr_data.x = Malloc(struct svm_node*, tr_data.l);

    for (int row = 0; row < tr_data.l; row++)
    {
        tr_data.y[row] = ta0.array[bar-row-1];
        //leak
        svm_node* tr_data_x_onerow = Malloc(svm_node, num_features+1);  
        tr_data_x_onerow[0].index = 1; tr_data_x_onerow[0].value = in0.array[bar-row-1];    tr_data_x_onerow[1].index = 2; tr_data_x_onerow[1].value = in1.array[bar-row-1];    tr_data_x_onerow[2].index = 3; tr_data_x_onerow[2].value = in2.array[bar-row-1];    tr_data_x_onerow[3].index = 4; tr_data_x_onerow[3].value = in3.array[bar-row-1];    tr_data_x_onerow[4].index = 5; tr_data_x_onerow[4].value = in4.array[bar-row-1];    tr_data_x_onerow[5].index = 6; tr_data_x_onerow[5].value = in5.array[bar-row-1];    tr_data_x_onerow[6].index = 7; tr_data_x_onerow[6].value = in6.array[bar-row-1];    tr_data_x_onerow[7].index = 8; tr_data_x_onerow[7].value = in7.array[bar-row-1];    tr_data_x_onerow[8].index = 9; tr_data_x_onerow[8].value = in8.array[bar-row-1];    tr_data_x_onerow[9].index = 10;
        tr_data_x_onerow[num_features].index = -1;      //Each row of properties should be terminated with a -1 according to the readme
        tr_data.x[row] = tr_data_x_onerow;
    }

…很少对tr_data进行操作…这行不通

    for (int row = 0; row <tr_data.l; row++)
    {
        free(tr_data_x_onerow);
    }
for (int row = 0; row <tr_data.l; row++)
{
    free(tr_data.x[row]);
}

但是请不要这样做。这是c++。使用vector或其他类似的集合

相关内容

  • 没有找到相关文章

最新更新