为什么 malloc 根本不分配内存?

Why doesn't malloc allocate memory at all?

我有以下结构:

struct block {
    void *addr; /*start address of memory for this block */
    int size;
    struct block *next;
};

我有以下代码来初始化每个块:

void block_init(struct block *b, void *addr, int size){

    /*Allocate space and fill b with the initial data.*/
    b = (struct block *)malloc(sizeof(struct block));
    if(b){
        b->addr = addr;
        b->size = size;
        b->next = NULL; 
    }    
}

我正在从另一个函数调用以下行:

struct block *list;
block_init(freelist, mem, size);

但是,它从不初始化块。

我用 gdb 来测试这个,但是每次我得到一个 NULL 指针:

123     b = (struct block *)malloc(sizeof(struct block);
(gdb) next
124     if(b){
(gdb) print b
 = (struct block *) 0x0
(gdb) print b->size
Cannot access memory at address 0x8

我不知道怎么回事,有人可以帮我吗?

你已经使用了block *,所以如果你改变b的值,它不会反映到调用函数。你应该使用 block**

void block_init(struct block **b /*HERE*/, void *addr, int size){

    /*Allocate space and fill b with the initial data.*/
    *b /*AND HERE*/ = (struct block *)malloc(sizeof(struct block));
    if(*b){
        (*b)->addr = addr;
        (*b)->size = size;
        (*b)->next = NULL; 
    }    
}

调用函数,

block_init(&list , mem, size);//pass by address

在不同意@pranit-kothari 所说的情况下,编写原始函数的一种可能更惯用的方式是

struct block* block_init(void *addr, int size) {
    /*Allocate space and fill b with the initial data.*/
    struct block* b = (struct block *)malloc(sizeof(struct block));
    if (b) {
        b->addr = addr;
        b->size = size;
        b->next = NULL; 
    }
    return b;
}

这避免了修改任何参数(我通常认为这是 'code smell'),读起来更清晰,调用起来可能更整洁。

(顺便说一句,malloc 参数应该是 size * sizeof(struct block) 吗?)