gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:28:14 26 4
gpt4 key购买 nike

我有以下结构:

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

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

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);

但是,它从不初始化 block 。

我用 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

我不知道发生了什么,有人能帮帮我吗?

最佳答案

你已经使用了block *,所以如果你改变b的值,它不会反射(reflect)到调用函数。你应该使用 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

关于c - 为什么 malloc 根本不分配内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28710882/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com