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

时间:2015-02-25 04:00:59

标签: c linux memory malloc heap-memory

我有以下结构:

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
$2 = (struct block *) 0x0
(gdb) print b->size
Cannot access memory at address 0x8

我不知道发生了什么,有人可以帮助我吗?

2 个答案:

答案 0 :(得分:4)

您已使用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

答案 1 :(得分:1)

如果不同意@ 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;
}

这可以避免修改任何参数(我通常觉得这是一种代码气味'),阅读起来比较清晰,并且调用可能更整洁。

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

相关问题