c - 为什么多次调用 calloc 会使我的应用程序崩溃?

标签 c memory memory-management

我有一个函数可以初始化包含嵌套结构和数组的结构。 在初始化结构时,我多次调用 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循环之前的日志,但程序崩溃了,并且循环内的第一个日志语句没有打印出来。

为什么会发生这种情况?

最佳答案

所以这可能不是您问题的答案,但这里是: 当我运行此代码(在 Ubuntu 上,gcc 7.4)并将所有 log 函数替换为 printf 时,它成功完成。我怀疑问题可能出在您使用日志功能的方式上。您指定它一直工作到循环内的第一个日志调用为止。您没有指定 log 函数的作用,或者它是一个函数还是只是 printf 的宏包装器,但您在循环内以不同的方式调用它- 第一个参数是 *state_struct 而不是格式字符串。

此外,您调用 calloc 的方式在语义上似乎不正确。第一个参数应该是您要分配的第二个参数大小的 block 数(在本例中大概是 1)

关于c - 为什么多次调用 calloc 会使我的应用程序崩溃?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59337633/

相关文章:

c - 有符号整数右移

c - 从 SDL 教程构建示例程序时出现 GCC 错误

objective-c - Objective-C - 内存管理和自动释放 ???

Objective-C NSThread 引用计数约定(保留与自动释放)

c - 在C编程中处理客户端-服务器套接字中的ctrl+c

c++ - 即使满足并输入退出条件,仍然打印错误消息

memory - 在 Spark 中,作业完成后内存中还剩下什么?

windows - Windows 任务管理器和任务列表中显示不同的内存使用情况

oracle - 如何确定选择查询的最佳提取大小

c - Compiler 是否优化了由 "malloc()"函数分配的内存?