0

I need to know how much memory used by process in linux. I used

FILE* file = fopen("/proc/self/maps", "r");

I read like this :

5606ee35c000-5606ee37d000 rw-p 00000000 00:00 0          [heap]
7fff502d9000-7fff502fa000 rw-p 00000000 00:00 0          [stack]

I have calculated memory map with this output like this:

Heap Size:135168
Heap Start Address: 5606ee35c000
Heap Finish Address:5606ee37d000
Stack Size:135168
Stack Start Address: 7fff502d9000
Stack Finish Address:7fff502fa000

But I used 10 byte stack(in function) and 50 byte heap(with malloc) in code. Why it shows 135168 byte. Can anybody help me?

Alperen
  • 1
  • 3
  • The kernel can _only_ give memory to a process in multiples of the _page_ size (e.g. 4096). And, for speed/efficiency when you ask for a small amount, it adds a minimum amount. Your size 135168 is 33 pages of 4096 bytes. To determine the number of bytes you are using, for stack, you'll need to look at differences in the stack pointer. For heap, you'll need to look at differences in `sbrk(0)`. But, you really have to look at the heap manager's internals (e.g. `malloc` et. al.). There may be some hooks. But, before `main` is called, there have been `malloc` calls, so it's not exact. – Craig Estey Apr 22 '20 at 17:08
  • Thank you for reply. I tried sbrk(0) at the beginning of the main function and at the end of the main function. The results are both same like "Heap Start Address: 5606ee35c000,Heap Finish Address:5606ee37d000". – Alperen Apr 23 '20 at 07:22
  • If I want to know data segment size and BSS of process. What should i do ? Because I cant see with that FILE* file = fopen("/proc/self/maps", "r"); – Alperen Apr 23 '20 at 07:24
  • There are special symbols defined: `__data_start`, `_edata`, `__bss_start`, and `_end`. You can do (e.g.) `extern char __data_start; extern char _edata;` Then, `size_t bytes_in_data = &_edata - &__data_start;` – Craig Estey Apr 23 '20 at 15:17
  • I think you should _edit_ your question and add [more] precise definitions of what you want to determine. Try to make the list as complete/inclusive as possible. Stick to needs vs solutions. There are other methods, such as parsing the output of `readelf` [or using the ELF library], that may be needed. But, at this point, _why_ do you want to know these values? And, what will you do with them? This can help determine how to go about it? Without this info, this is beginning to seem like an XY problem: http://mywiki.wooledge.org/XyProblem – Craig Estey Apr 23 '20 at 15:20

0 Answers0