How free() knows , how many bytes of memory freed?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Prabhakar Rao
    New Member
    • Aug 2008
    • 2

    How free() knows , how many bytes of memory freed?

    For ex if memory allocated like below

    p = malloc(100)
    . . . . .

    free(p)

    how the free routine know, how much memory to be freed?
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    100 bytes.

    That's what was allocated.

    Comment

    • boxfish
      Recognized Expert Contributor
      • Mar 2008
      • 469

      #3
      Hi,
      The operating system keeps a table that contains information on where memory was allocated and how much. When you deallocate memory, the operating system just deletes an entry from its allocation table. I'm not 100% sure that's how it works though.
      Hope this helps.

      Comment

      • gpraghuram
        Recognized Expert Top Contributor
        • Mar 2007
        • 1275

        #4
        If you have K&R C Book....there is a chapter which discuss about the data structure of this.
        Raghu

        Comment

        • JosAH
          Recognized Expert MVP
          • Mar 2007
          • 11453

          #5
          Originally posted by boxfish
          Hi,
          The operating system keeps a table that contains information on where memory was allocated and how much. When you deallocate memory, the operating system just deletes an entry from its allocation table. I'm not 100% sure that's how it works though.
          Hope this helps.
          The OS hasn't much to do with it; the OS simply allocates pages and assigns
          them to the process; malloc and friends turn that raw memory into a 'heap'
          from which malloc takes memory and free returns it again. Most (if not all)
          implementations prepend a small block to the allocated block in which the size
          of the block is stored. The free() function uses that information when it has to
          return that block to the heap again.

          kind regards,

          Jos

          Comment

          • Prabhakar Rao
            New Member
            • Aug 2008
            • 2

            #6
            Originally posted by JosAH
            The OS hasn't much to do with it; the OS simply allocates pages and assigns
            them to the process; malloc and friends turn that raw memory into a 'heap'
            from which malloc takes memory and free returns it again. Most (if not all)
            implementations prepend a small block to the allocated block in which the size
            of the block is stored. The free() function uses that information when it has to
            return that block to the heap again.

            kind regards,

            Jos

            Thanks all for the replies.

            Comment

            Working...