2016-11-16 115 views
1

我试图使用包含动态数组的结构的动态数组。 分配在函数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))); 

,所以我不知道应该怎么办,为什么:

+0

尝试先运行一个像valgrind的内存调试器。 –

回答

0

(顺便说一句,在C你不需要输入malloc()的返回值:如果它没有编译就没有编译,你就犯了一个错误)

你觉得奇怪的代码涉及到al将所有阵列定位在单个缓冲区中:这允许更好的“存储器局部性”(即,以不能单独修改数组为代价):这对性能有好处,但对于一次初始化并且不随时间变化的数据有用(或者至少其大小不随时间变化)。

它也可以让你只用一个电话整件事自由地free(),使错误处理更加简单(因为你没有检查,在一个循环中的所有malloc()调用成功,如果没有,自由所有呼叫到目前为止成功,而不是其他...)