【问题标题】:allocate dynamic structure array分配动态结构数组
【发布时间】:2017-03-30 11:08:29
【问题描述】:

我正在尝试使用包含动态数组的结构的动态数组。 分配在函数 build_resuts 中完成,内存在函数 free_data 中释放。

我这样做对吗?

typedef struct InputResultsLine 
{
    long registered;
    long *candidates;
} InputResultsLine;

void func()
{
    InputResultsLine *data, totals;
    int nbPollingPlaces = 10;

    build_results(&data, &totals,  5, nbPollingPlaces);     

    free_data(&data, &totals, nbPollingPlaces); 
}

void build_results(InputResultsLine **data, InputResultsLine *totals, int nbCandidates, int nbPollingPlaces)
{   
    int i;
    InputResultsLine *ptrCurrentLine;

    totals->candidates = (long*) malloc(nbCandidates * sizeof(long));       

    *data = (InputResultsLine*) malloc(nbPollingPlaces * sizeof(InputResultsLine));

    for(i = 0; i < nbPollingPlaces; i++)
    {       
        ptrCurrentLine = &((*data)[i]);
        ptrCurrentLine->candidates = (long*) malloc(nbCandidates * sizeof(long));

        // [...]    
    }   
}

void free_data(InputResultsLine **data, InputResultsLine *totals, int nbPollingPlaces)
{
    int i;  

    for(i = 0; i < nbPollingPlaces; i++)
    {
        free(((*data)[i]).candidates);
    }

    free(totals->candidates);
    free(*data);
}

我看到了分配的样本:

*data = (InputResultsLine*) malloc(nbPollingPlaces * (sizeof(InputResultsLine) + nbCandidates * sizeof(long)));

所以我不确定我应该怎么做以及为什么:

【问题讨论】:

  • 先尝试运行像 valgrind 这样的内存调试器。

标签: c arrays malloc dynamic-allocation


【解决方案1】:

(顺便说一句,在 C 中你不需要强制转换 malloc() 的返回值:如果没有强制转换就无法编译,那么你就犯了一个错误)

您觉得奇怪的代码涉及在单个缓冲区中分配所有数组:这允许更好的“内存局部性”(即相关事物在内存中在一起),但代价是无法单独修改数组:这对性能有好处但仅适用于初始化一次且不随时间变化的数据(或至少其大小不随时间变化的数据)。

它还允许您只调用一次free() 就可以释放整个事情,并使错误处理更加简单(因为您不必检查循环中的所有malloc() 调用是否成功,如果没有,释放迄今为止成功的所有调用,而不是其他调用......)

【讨论】:

    猜你喜欢
    • 2021-10-30
    • 1970-01-01
    • 2019-07-19
    • 2020-03-06
    • 2012-03-25
    • 2011-12-13
    相关资源
    最近更新 更多