Thread: another malloc question

  1. #1
    Registered User
    Join Date
    Oct 2001
    Posts
    21

    another malloc question

    ok, here goes...
    If I have fp = malloc(3*sizeof(int)); fp now points to the memory address of the first int of 3 that have been allocated for my use. When I use free(fp); it frees those 3 ints.

    How does it know that 3 ints worth of space need to be freed? All I passed in was a pointer to the first one. Is there some sort of marker in memory that says this is where a set of allocated memory ends? Or is this kept track of somewhere else?

    i.e. if I were to advance the pointer by one int fp = fp+sizeof(int); and then free(fp); would the 2 remaining ints be freed? or would 3 ints be freed? or would I get some sort of error?

    sorry I don't understand malloc yet, thanks for any help,

    (: Ian

  2. #2
    Blank
    Join Date
    Aug 2001
    Posts
    1,034
    I know that malloc uses the brk system call.
    Ofcourse you can read the source code.

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    What malloc hides from you is a linked list of allocated blocks, and a linked list of free blocks.

    Each node in each of these lists is a pointer to the block, and the size of the block.

    So when you free a block, it looks for the correct pointer (through the allocated list), then moves that to the free list (along with its size).

    That's the basics - actual implementations vary (like they will try and merge adjacent free blocks into one larger block).
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  4. #4
    Banned Troll_King's Avatar
    Join Date
    Oct 2001
    Posts
    1,784
    if I were to advance the pointer by one int fp = fp+sizeof(int); and then free(fp); would the 2 remaining ints be freed? or would 3 ints be freed? or would I get some sort of error?
    Error.

  5. #5
    Registered User
    Join Date
    Oct 2001
    Posts
    21

    Thanks!

    Thanks for all the input guys, it makes a lot more sense to me now.


    (: Ian

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. malloc + segmentation fault
    By ch4 in forum C Programming
    Replies: 5
    Last Post: 04-07-2009, 03:46 PM
  2. another do while question
    By kbpsu in forum C++ Programming
    Replies: 3
    Last Post: 03-23-2009, 12:14 PM
  3. Alternative to malloc
    By stellastarr in forum C Programming
    Replies: 13
    Last Post: 04-30-2007, 04:10 PM
  4. malloc, calloc question
    By chen1279 in forum C Programming
    Replies: 12
    Last Post: 09-07-2006, 05:54 PM
  5. Question about malloc()
    By cdalten in forum C Programming
    Replies: 6
    Last Post: 05-12-2006, 10:57 AM