gpt4 book ai didi

c - 动态分配的内存发生了奇怪的事情

转载 作者:太空宇宙 更新时间:2023-11-03 23:51:06 24 4
gpt4 key购买 nike

我实现了这个函数来创建一个部门 d 和分支因子 b 的树:

void create(node *n, int b, int d){
int cont,i;


if(d>0){
n->children = (node *) malloc(b*sizeof(node));

if(!n->children){
printf("\n\nMemory couldn't be allocated\n");
getchar();
return;
}
n->alpha = -100;

for(i=0;i<b;i++){
create((n->children+i*sizeof(node)), b, d-1);

}
}
else if(d==0){
if(n){
n->alpha = rand()%9 + 1;
printf("%d ",n->alpha);
}

}

它适用于 d<6 和 b<6,但当 b =6 和 d=6 或更大时,它会给我一个段错误。

但是当我将 create((n->children+i*sizeof(node)), b, d-1); 行更改为 create((&n->children[i]), b, d-1);,据我测试,它适用于任何 d 和 b。但这两条线真的是一样的!!!只是 child 结构的地址……那么,有人知道为什么会这样吗? malloc 不会分配一个连续的内存块吗?

这件事真的让我很困惑!!请帮助!

谢谢 =) ,

英格丽

最佳答案

你已经回答了你的问题。 :D

But when I change the line create((n->children+i*sizeof(node)), b, d-1); for the line create((&n->children[i]), b, d-1);, it works perfectly for any d and b, as far as I have tested. But the two lines truly are the same!!! just the address of the children struct

这两行是因为指针运算考虑了对象的类型,并且它根据该对象类型的大小正确地调整了结果地址。所以:

   n->children+i === &n->children[i]

两者都转换为 (n->children)+ (i * sizeof(struct node))同时,您的代码:

(n->children+i*sizeof(node)

获取转换为 (n->children)+ (i * sizeof(struct node))*sizeof(struct node)。第一个 sizeof 运算符是你错误添加的,而第二个是指针算法自动添加的。

It works fine for d<6 and b<6, but when b =6 and d=6, or bigger, it gives me a segmentation fault.

它适用于小数目,因为 malloc 函数在进程空间中映射的内存比出于性能原因所需的内存多。当您超出正确映射的内存区域时,您会遇到段错误。

Doesn't malloc allocates one contiguous block of memory?

是的,malloc 分配一个连续的内存块。

关于c - 动态分配的内存发生了奇怪的事情,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19688768/

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