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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With