While writing c code I noticed that when I change the value associated with memory location pointed to by pointer x, it results in a change of value of the data pointed to by pointer y.
When I checked again I found that malloc is allocating overlapping regions of memory for to 2 different pointers. Why is this happening??
I have quite a few dynamically allocated variables in my code. So is it because there is a limit to the maximum amount of memory that can allocated by malloc?
The following is an output from my code. From the output you can see that malloc allocates overlapping memory regions to x and y.
size x:32 y:144 //total size allocated to x and y by malloc
//the memory locations allocated to each of the pointers
location x:0x7fb552c04d20 y:0x7fb552c04c70
location x:0x7fb552c04d24 y:0x7fb552c04c8c
location x:0x7fb552c04d28 y:0x7fb552c04ca8
location x:0x7fb552c04d2c y:0x7fb552c04cc4
location x:0x7fb552c04d30 y:0x7fb552c04ce0
location x:**0x7fb552c04d34** y:0x7fb552c04cfc
location x:0x7fb552c04d38 y:0x7fb552c04d18
location x:0x7fb552c04d3c y:**0x7fb552c04d34**
The code i used for allocating memory is
int *x = (int *)malloc((DG_SIZE+1)*sizeof(int));
int *y = (int *)malloc(4*(DG_SIZE+2)*sizeof(int));
printf("\n size x:%d y:%d\n", (DG_SIZE+1)*sizeof(int), 4*(DG_SIZE+2)*sizeof(int));
int a = 0;
for(a = 0; a <= DG_SIZE; a++){
printf("\n location x:%p y:%p\n",(x + a), (y + a*DG_SIZE + 0));
}