Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I force memory cleanup in C#?

I heard that C# does not free memory right away even if you are done with it. Can I force C# to free memory?

I am using Visual Studio 2008 Express. Does that matter?

P.S. I am not having problems with C# and how it manages memory. I'm just curious.

like image 753
jim Avatar asked Dec 05 '09 18:12

jim


People also ask

How do I free up memory on C?

“free” method in C is used to dynamically de-allocate the memory. The memory allocated using functions malloc() and calloc() is not de-allocated on their own. Hence the free() method is used, whenever the dynamic memory allocation takes place. It helps to reduce wastage of memory by freeing it.

What happens if you don't free memory in C?

If free() is not used in a program the memory allocated using malloc() will be de-allocated after completion of the execution of the program (included program execution time is relatively small and the program ends normally).

What happens when you free memory in C?

The C standard defines the behavior of the free function: The free function causes the space pointed to by ptr to be deallocated, that is, made available for further allocation. which means that a later call to malloc (or something else) might re-use the same memory space.


1 Answers

Jim,

You heard correctly. It cleans up memory periodically through a mechanism called a Garbage Collector. You can "force" garbage collection through a call like the one below.

GC.Collect();

I strongly recommend you read this MSDN article on garbage collection.

EDIT 1: "Force" was in quotes. To be more clear as another poster was, this really only suggests it. You can't really make it happen at a specific point in time. Hence the link to the article on garbage collection in .Net

EDIT 2: I realized everyone here only provided a direct answer to your main question. As for your secondary question. Using Visual Studio 2008 Express will still use the .net framework, which is what performs the garbage collection. So if you ever upgrade to the professional edition, you'll still have the same memory management capabilities/limitations.

Edit 3: This wikipedia aritcles on finalizers gives some good pointers of what is appropriate to do in a finalizer. Basically if you're creating an object that has access to critical resources, or if you're consuming such an object, implement IDispose and/or take advantage of the using statement. Using will automatically call the Dispose method, even when exceptions are thrown. That doesn't mean that you don't need to give the run finalizers hint...

like image 93
Jason D Avatar answered Sep 23 '22 16:09

Jason D