# memory allocation

This is a discussion on memory allocation within the C Programming forums, part of the General Programming Boards category; I might not be fully understanding what's going on here, but when I allocate two segments of memory for two ...

1. ## memory allocation

I might not be fully understanding what's going on here, but when I allocate two segments of memory for two variables, the address difference between the two doesn't seem to account for the amount of space that I'm allocating.

Code:
```int
main(int argc, char* argv[]) {

int *foo = malloc(4*sizeof(int));
int *bar = malloc(sizeof(int));

printf("foo: &#37;X\n", (unsigned int) foo);
printf("bar: %X\n", (unsigned int) bar);

return 0;

}```
Output:

Code:
```foo: 100120
bar: 100130```
Given that I'm allocating 4 x sizeof(int) for foo (16 bytes), and assuming that allocation is contiguous, I'm expecting there to be a separation of at least 16 between the output for foo and bar (i.e. 100120 and 100136). What am I missing? Thanks in advance!

2. The difference between 100136 and 100120 is twenty-two bytes. The difference between 100130 and 100120 is sixteen bytes. (Look at your format specifier.)

3. Originally Posted by tabstop
The difference between 100136 and 100120 is twenty-two bytes. The difference between 100130 and 100120 is sixteen bytes. (Look at your format specifier.)
Thanks for the tip on the format specifier. Changing it to %d gave me the information that I had expected to see.

I do have another question, though. How did you come to the conclusion that there were sixteen bytes between 100130 and 100120 (apologies for being dense).

4. Who says that the two blocks must be right next to each other? Theoretically, malloc() can allocate anywhere from the heap, giving the appearance of a huge gap between memory.

5. It's always easy to make such a mistake. Your two Hexadecimal values converted to decimal differ by 16.

6. That's why I said look at your format specifier: %x means "print this unsigned integer as a hexadecimal integer." (That's also why you got a warning about passing a pointer as an integer without a cast.) The format specifier for pointers is %p, and is system-specific (but is also often hexadecimal).

7. Originally Posted by MacGyver
Who says that the two blocks must be right next to each other? Theoretically, malloc() can allocate anywhere from the heap, giving the appearance of a huge gap between memory.
Yes, I understand that. But in this case, the gap seemed pretty close, and I was trying to understand why I wasn't seeing 16 bytes in between the two numbers.

Popular pages Recent additions