#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2013
    Posts
    2
    Rep Power
    0

    Dynamic allocation problem


    Hi there, I'm new so hello everyone.
    I'm in my first year in college and we're learning C,
    I'm writing a program and I'm doing some functions that need to do dynamic allocation.
    my question is where do I need to do the "free" func, in the function itself or in the MAIN?
    I was looking in google and I saw different thing every time.
    tanks!
  2. #2
  3. Contributing User
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2003
    Location
    USA
    Posts
    7,184
    Rep Power
    2222
    Where you call free() all depends on what you're doing. The main question you need to ask your would be: When do I no longer need the memory that I had allocated?

    If what you allocate will only be used inside the function where you malloc it, then of course you would free it before you return from that function.

    But if that malloc'd memory needs to be used by the rest of the program, then you cannot free it in the function, since you'd be destroying something that's still needed. So then elsewhere in the program when you know that that memory will no longer be needed, that is where you would free it instead. If that's in main(), then so be it.

    Here's a scenario: your program creates and uses a linked list (if you don't know what that is, don't worry: you'll encounter it soon enough). In a linked list, you malloc list entries (called "nodes") that you then link into the list using pointers. One of the operations you can perform on a linked list is to delete a node, so you write a function to find the node in the list, to remove it from the list, and to free that node. In this case, you would free that malloc'd memory in a function whose purpose is to delete a node.

    So there really isn't any set answer to your question. It all depends on what your program does. If in doubt, just ask yourself whether the program is done with that malloc'd memory.
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2013
    Posts
    2
    Rep Power
    0
    Thanks a lot!

IMN logo majestic logo threadwatch logo seochat tools logo