In the following program, the address allocated by the realloc falls in the address range allocated by malloc. I am not able to understand why. (Please overlook freeing of memory.)
#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;
}
output:
addr range of node: 0xa2a010 <--> 0xa2a070
addr recvd by tmp: 0xa2a030
33.132100 32.230000
Executed on x64 Linux.
struct node* ptr =(struct node*)malloc(sizeof(struct node*));should be
struct node* ptr =(struct node*)malloc(sizeof(struct node));