Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

malloc allocating the same memory location to 2 pointers

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));
}
like image 244
Johns Paul Avatar asked Jan 17 '26 06:01

Johns Paul


1 Answers

The y block is wholly before the x block in memory. There's no overlap.

However your loop is printing out addresses from beyond the end of the y block, into the y column.

Specifically:

int *y = (int *)malloc(4*(DG_SIZE+2)*sizeof(int));

has allocated 36 ints, because DG_SIZE is 7 (based on your output).

But then you loop a from 0 to 7 and output (y + a*DG_SIZE + 0). When a == 6, this gives y + 42 which is beyond the end of the 36 ints allocated.

I guess you meant to output y + a*4, rather than y + a*DG_SIZE.

like image 70
M.M Avatar answered Jan 19 '26 18:01

M.M



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!