我有一个函数,用于初始化包含嵌套结构和数组的结构。
初始化结构时,我多次调用calloc
。
请参阅下面的代码:
typedef struct
{
int length;
uint8_t *buffer;
} buffer_a;
typedef struct
{
int length;
uint8_t *buffer;
int *second_buffer_size;
uint8_t **second_buffer;
} buffer_b;
typedef struct
{
int max_length;
buffer_a *buffer_in;
buffer_b *buffer_out;
} state_struct;
state_struct *init(int size, int elements) {
size_t struct_size = sizeof(state_struct);
state_struct *s = (state_struct*) calloc(struct_size, struct_size);
log("Building state with length %d", size);
s->max_length = size;
size_t buffer_in_size = s->max_length * sizeof(buffer_a);
s->buffer_in = (buffer_a*) calloc(buffer_in_size, buffer_in_size);
size_t buffer_out_size = s->max_length * sizeof(buffer_b);
s->buffer_out = (buffer_b*) calloc(buffer_out_size, buffer_out_size);
log("Allocated memory for both buffers structs");
for (int i = 0; i < s->max_length; ++i) {
size_t buf_size = elements * sizeof(uint8_t);
s->buffer_in[i].buffer = (uint8_t*) calloc(buf_size, buf_size);
s->buffer_in[i].length = -1;
log(s, "Allocated memory for in buffer");
s->buffer_out[i].buffer = (uint8_t*) calloc(buf_size, buf_size);
s->buffer_out[i].length = -1;
log(s, "Allocated memory for out buffer");
size_t inner_size = elements * elements * sizeof(uint8_t);
size_t inner_second_buffer_size = elements * sizeof(int);
s->buffer_out[i].second_buffer = (uint8_t**) calloc(inner_size, inner_size);
s->buffer_out[i].second_buffer_size = (int*) calloc(inner_second_buffer_size, inner_second_buffer_size);
log(s, "Allocated memory for inner buffer");
}
return s;
}
仅打印for循环之前的日志,但程序崩溃,并且循环内的第一个log语句也不会输出。
为什么会这样?
答案 0 :(得分:1)
因此,这可能不是您所提问题的答案,但是这里有:
当我运行此代码(在Ubuntu,gcc 7.4上)并将所有log
函数替换为printf
时,它成功完成了。我怀疑问题可能出在您使用日志功能的方式上。您指定它可以工作直到循环内的第一个日志调用。您没有指定log
函数的功能,也没有指定它是printf
的函数还是宏包装器,但是您在循环内以不同的方式调用它-第一个参数是{ {1}},而不是格式字符串。
此外,您呼叫*state_struct
的方式在语义上似乎不正确。第一个参数应该是您要分配的第二个参数大小的块数(在这种情况下,大概是1个)