-1

Now, when I print each element in my block array, each one has the same address. For example:

ints:   20 bytes stored at 0xbffa84fc 
doubles:   80 bytes stored at 0xbffa84fc 
chars:   8 bytes stored at 0xbffa84fc 
Students:   1008 bytes stored at 0xbffa84fc
theGuy05
  • 417
  • 1
  • 7
  • 22
  • 1
    Improved with the print code added. But remember that a true ["Minimal, Complete, Verifiable Example"](http://stackoverflow.com/help/mcve) can be copy-pasted and compiled. So that means proper includes and definitions for HeapType and BlockType, and `#include `. Then ask: could you demonstrate the problem confusing you with less? You have four `mh_alloc` calls...what's special about 4 that 2 couldn't prove? Do they need "int" and "double" types or can you pare it down? Less is more and you may find the problem yourself! – HostileFork says dont trust SE Oct 28 '14 at 01:33
  • possible duplicate of [Simple C implementation to track memory malloc/free?](http://stackoverflow.com/questions/852072/simple-c-implementation-to-track-memory-malloc-free) – theGuy05 Jan 09 '15 at 15:27

2 Answers2

6
blk->addr = &blk;

The address of the allocated memory actually is blk itself. But here, you are using &blk, i.e, the address of blk.

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
0

malloc returns a void pointer.

Here it returns a void pointer to 'blk', however typecasted to data type 'BlockType'. So,'blk' already holds the address of allocated memory, but the statement 'blk->addr = &blk' points to the address of 'blk' which is obviously going to be the same.

Karthik Balaguru
  • 7,424
  • 7
  • 48
  • 65
  • I wouldn't go so far as "obvious". At an implementation level there is no obligation for local variables in functions to be at the same address on different calls. It *happens* to be true in this case, and will often be in this call pattern due to how most compilers are implemented... but one shouldn't rely upon that. (Consider for instance what if the function contained a variable length array...?) – HostileFork says dont trust SE Oct 28 '14 at 02:04
  • Yes, i was also referring to the same point only but did not mention it explicitly. – Karthik Balaguru Oct 28 '14 at 02:07