Clarification in free

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • manjuks
    New Member
    • Dec 2007
    • 72

    Clarification in free

    Hi All,

    Assume we have allocated 100 bytes of memory using malloc,
    We will get a pointer to the allocated memory, to free up this memory we will pass this pointer to free function. My question is how free will come to know that it needs to free 100 bytes of memory? where it gets this information?

    Thanks,
    Manjunath
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    That is implementation defined, which means that every implementation is free to store that data, and any other data it requires to function anyway it chooses. 2 common methods are
    1. malloc actually allocates more than the 100 requested bytes. It allocates a block header plus the 100 bytes, the block header is fixed size and located in memory before the returned block, it contains the block size among other things. because the header is a fixed size the start of it can be easily calculated from the block pointer.
    2. The malloc routines keep a table or list of all allocated memory, when you malloc it adds an entry to the table with details such as block size. When you free it looks up the blocks entry in the table to get the block size.


    These are 2 common methods, however there are probably others. You should make no assumption about how malloc may store the additional memory it requires to perform its function in allocating and freeing memory.

    Comment

    • manjuks
      New Member
      • Dec 2007
      • 72

      #3
      Very useful.

      Thanks
      Manjunath

      Comment

      Working...