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)));
,所以我不知道应该怎么办,为什么:
尝试先运行一个像valgrind的内存调试器。 –