在下面的程序中,realloc分配的地址落在malloc分配的地址范围内。我不明白为什么。 (请忽略内存的释放。)
#include<stdio.h>
#include<stdlib.h>
struct MyClass
{
double num;
};
struct node
{
MyClass* array;
int max_size;
double w[10]; //used only to increase the size of node
long double ld;
};
void fill(struct node *ptr)
{
MyClass *tmp;
if(ptr->array==NULL )
tmp = (MyClass*)realloc(ptr->array, 10*sizeof(MyClass) );
printf("addr range of node: %p <--> %p\n", ptr, &(ptr->ld));
printf("addr recvd by tmp: %p\n", tmp);
if(tmp)
{
ptr->array=tmp;
ptr->array[0].num=32.23;
ptr->ld = 33.1321;
}
}
struct node*
allocator()
{
struct node* ptr =(struct node*)malloc(sizeof(struct node*));
ptr->max_size= 232;
ptr->ld =321.3425;
ptr->array = __null;
return ptr;
}
int
main()
{
struct node *ptr =allocator();
fill(ptr);
printf(" %Lf %lf\n", ptr->ld, ptr->array[0].num);
return 0;
}
输出:
addr range of node: 0xa2a010 <--> 0xa2a070
addr recvd by tmp: 0xa2a030
33.132100 32.230000
在 x64 Linux 上执行。
最佳答案
结构节点* ptr =(结构节点*)malloc(sizeof(结构节点*));
应该是struct node* ptr =(struct node*)malloc(sizeof(struct node));
关于c - 关于重新分配的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6730171/