December 15th, 2013, 01:46 PM
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.
December 15th, 2013, 02:36 PM
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.
December 15th, 2013, 02:52 PM