Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i get memory size allocated by my program?

Tags:

c++

c

memory

opencv

qt

I write my project by c with opencv. I want print info about allocated memory or memory used by my program. Is there a functions, that give me the information about the memory ? Finally I'm using Qt for Linux and Windows ,

Thanks in advance.

like image 422
Aym Avatar asked Sep 21 '12 13:09

Aym


People also ask

How much memory is allocated for a program?

This is data for which memory is being allocated while executing the program. In C++, this allocation is usually performed by the malloc function or new operator. In 32-bit programs the size of dynamically allocated memory is restricted to 2 Gbytes, in 64-bit programs to 8 Tbytes.

How can you determine the size of an allocated portion of memory?

Q) How can you determine the size of an allocated portion of memory? In C language, we can calculate the size of the static array using the sizeof operator but there is no operator to calculate the size of the dynamically allocated memory. So using some trick we can get the size of the allocated array.

How can you tell the size of memory allocated by malloc using pointers?

It is impossible to know how much memory was allocated by just the pointer. doing sizeof (p) will get the size of the pointer variable p which it takes at compile time, and which is the size of the pointer. That is, the memory the pointer variable takes to store the pointer variable p .

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

Linux glibc sysconf(_SC_AVPHYS_PAGES) and get_avphys_pages() 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.


2 Answers

On Linux you look into your own process info pseudo-file:

/proc/[pid]/statm
Provides information about memory usage, measured in pages. The columns are:
size       total program size
           (same as VmSize in /proc/[pid]/status)
resident   resident set size
           (same as VmRSS in /proc/[pid]/status)
share      shared pages (from shared mappings)
text       text (code)
lib        library (unused in Linux 2.6)
data       data + stack
dt         dirty pages (unused in Linux 2.6)

On Windows you look at you own process Process Object performance counters:

Private Bytes Shows the current number of bytes that this process has allocated that cannot be shared with other processes.

like image 68
Remus Rusanu Avatar answered Sep 30 '22 22:09

Remus Rusanu


You can write wrappers to malloc and free that track how much memory you're using.

EDIT: If you also want to intercept calls to malloc and free in external libraries, you will have to define them in a shared library and load it before libc. How you do this depends on your OS.

like image 25
Dan Avatar answered Sep 30 '22 21:09

Dan