Thread: malloc and free usage

  1. #1
    Registered User
    Join Date
    Jun 2009
    Posts
    56

    malloc and free usage

    Hi all,

    I know that each time we allocate memory onto the heap (malloc, calloc, realloc..) once we finish we have to free it in order to avoid memory leaks.

    Just to improve my skills I'm reading the C code of paste.c (the linux command). Now without go through code details, why in the code I see a couple of xmalloc and there are no free() call?
    Shouldn't we free the memory we allocated?

    Thanks in advance

  2. #2
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    Generally, yes, it is advisable to ensure your programs explicitly release all memory they allocate. Not everyone does it though. With some it is a calculated (hopefully low) risk. With others, it is laziness or incompetence.

    "Advisable" is not the same as "mandatory".

    The unix past command is pretty simple. Given that, the developers may have decided decided to be lazy about memory deallocation, and rely on the operating system cleaning up when the program exits.

    Another possibility is that the program calls realloc(). If the size supplied to realloc() is zero, it has the same net effect as free().
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

  3. #3
    Registered User
    Join Date
    Jun 2009
    Posts
    56
    Hi,

    thanks for your help I appreciate it

  4. #4
    Kiss the monkey. CodeMonkey's Avatar
    Join Date
    Sep 2001
    Posts
    937
    It is also important to keep in mind how long your program will be running. For scientific applications, or server-side stuff, a program may regularly (constantly) allocate resources and run for weeks. Then what happens? In my humble opinion, all memory should be explicitly deallocated when it is no longer needed.
    "If you tell the truth, you don't have to remember anything"
    -Mark Twain

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Correct usage of malloc and free for 2D array
    By disruptivetech in forum C Programming
    Replies: 1
    Last Post: 10-20-2008, 05:20 AM
  2. MALLOC function usage prob
    By nishkarsh in forum C Programming
    Replies: 17
    Last Post: 09-01-2008, 03:43 AM
  3. Malloc - Free giving double free or corruption error
    By andrew.bolster in forum C Programming
    Replies: 2
    Last Post: 11-02-2007, 06:22 AM
  4. Correct usage of malloc()
    By cboard_member in forum C++ Programming
    Replies: 9
    Last Post: 07-24-2005, 06:28 AM
  5. free() usage
    By pdstatha in forum C Programming
    Replies: 5
    Last Post: 03-13-2002, 09:28 AM