Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

free and malloc question

Status
Not open for further replies.

dwhalen

Programmer
Feb 22, 2002
105
CA
Hey,

I am new to C and I am writing a small program similar to grep. I am using some linked list structures so I don't have to have a staticly defined array. I use malloc to create each new structure. What I am wondering is, do I have to call free on each pointer when the program ends? I read that you have to call free or you will have a memory leak. But in the examples I read in some books K&R Programming C and pratical C, they don't usually call free. When my program ends will the memory be freed up? Or will more and more memory get eaten up each time I run my program? Do give you an idea of the code:
Code:
//this is a structure for our file information
struct file_info
{
    char *filename;//name of the file
    unsigned long matches;
   // struct line_info *
    struct file_info *next; //the next file
} files;

/* So I will start off with one file and with each
new file use malloc to create a pointer to a new 
file_info structure and make next point to it.
*/

Hope this made sense.

Thanks for any help.

Later
 
> I read that you have to call free or you will have a memory leak
This is true - every malloc should have exactly one free.

> do I have to call free on each pointer when the program ends?
Most good operating systems will do this for you.
However, the practice of doing it will mean you know what to do when you really have to tidy up when your code exits. For example, someone decides to use your code inside a larger program.

--
 
Thanks for the answer. So just to be clear, if I don't call free on all my malloced pointers when the program ends the OS will "probably" free up the memory for me anyway, but I should really do it myself just in case another program calls my program. Plus it is just good coding practices. Ok, that makes sense.

Oh, btw, thanks for that link, I have bookmarked that site.

Later
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top