Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C - Check currently available free RAM?

I know how to use malloc() and free() to allocate memory, but is there also a standard C function to check how much memory is left, so I can call that periodically to make sure my code has no memory leaks?

The only thing I can think of is calling malloc(1) in a endless loop until it returns an error, but shouldn't there be a more efficient way?

like image 549
Maestro Avatar asked Jan 17 '13 19:01

Maestro


People also ask

How can I find out how much memory is available in C?

These two glibc extensions should give you the available number of pages. We can then just multiply that by the pages size sysconf(_SC_PAGESIZE) to find the total available memory in bytes.

How can I free up RAM in C?

You have to free() the allocated memory in exact reverse order of how it was allocated using malloc() . Note that You should free the memory only after you are done with your usage of the allocated pointers.

What is available memory in free?

Free memory, which is memory available to the operating system, is defined as free and cache pages. The remainder is active memory, which is memory currently in use by the operating system. The Disk And Swap Space Utilization page, shown in Figure 9.2, shows system resources use, including disk and swap space use.

How do I free up RAM on Linux?

The most common way you'll see on the web to check for free memory in Linux is by using the free command. Using the free -m command to check your Linux memory usage, displays the values as MB instead of KB. The free column beside -/+ buffers/cache with 823 MB is the actual free memory available to Linux.


1 Answers

No, there's no standard C function to do that. There are some platform-specific functions you can use to perform certain types of queries (like working set size), but those probably won't be helpful, because sometimes memory which has been properly free()d is still considered to be allocated by the OS because the malloc implementation might keep the freed memory around in a pool.

If you want to check for memory leaks, I highly recommend using a tool like Valgrind, which runs your program in a virtual machine of sorts and can track memory leaks, among other features.

If you're running on Windows, you can use _CrtDbgReport and/or _CrtSetDbgFlag to check for memory leaks.

like image 87
Adam Rosenfield Avatar answered Oct 20 '22 02:10

Adam Rosenfield