请看c代码并帮助我。为什么我有“free(): invalid next size (fast)”?我尝试了 valgrind,但不明白,有太多“无效的写入/读取 ....”,但如果我评论 free_array(all) a 有正确的答案。它只是所有代码的一部分。
#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>
#include <stdlib.h>
struct pair {
uint32_t num;
uint32_t effect;
};
struct array {
size_t size;
struct pair data[];
};
size_t sizeof_array(size_t size)
{
return sizeof(struct array) + (size * sizeof(uint32_t));
}
struct pair *create_pair(uint32_t i, uint32_t eff)
{
struct pair *ret = calloc(2, sizeof(uint32_t));
if (! ret)
abort();
ret->num = i;
ret->effect = eff;
return ret;
}
struct array *create_array(size_t size)
{
struct array *ret = calloc(1, sizeof_array(size));
if (! ret)
abort();
ret->size = size;
return ret;
}
void free_array(struct array *array)
{
// size_t i;
// for (i = 0; i < array->size; ++i) {
// free(&array->data[i]);
// }
free(array);
}
int main()
{
int eff;
size_t n;
scanf("%zu", &n);
struct array *all = create_array(n);
size_t i;
for(i = 0; i < n; ++i) {
scanf("%d", &eff);
all->data[i] = *create_pair(i, eff);
}
free_array(all);
return 0;
}