Question

I'm writing a C++ program (compiled with gcc and running on RedHat Linux). The program needs to know at runtime how much space is left on the stack and how much is left in the heap. I realize there may not be a definite answer to this question (about the heap), so alternatively, I could use the amount of memory already allocated from the heap instead. Is there a a library/system function call that will give me this data?

I'd like to add that I only need this for debugging purposes, and only need rough estimates, so quick-and-dirty solutions are perfectly acceptable. However, I need to query the memory usage very frequently, so shelling out to a Unix cmd-line utility and parsing its output is not acceptable.

No correct solution

OTHER TIPS

You probably can create your own new and delete functions that encapsulates the real new and delete operators and take note of the memory usage at the same time.

For stack, there's a trick in C where you take a look at the address of the first local variable defined in your current function to get a rough idea about where the stack pointer is at the moment. I guess it should work in C++ but haven't tried it.

on linux you can read /proc/pid/status

Be aware that on 32-bit systems, the stack grows downwards and the heap grows upwards, and the two might meet somewhere in the middle. The space might, therefore, be allocated to stack or to heap, but not to both at the same time. Note that shared memory segments (if you use them) complicate the memory map. So can dynamically loaded (shared) libraries.

+------------+
|    stack   | high addresses
|      |     |
|      v     |
+------------+
|            |
|   unused   |
|            |
+------------+
|            |
|      ^     |
|      |     |
|    heap    |
|            |
+------------+
|            |
|     bss    |
|            |
+------------+
|            |
|    data    |
|            |
+------------+
|            |
|    text    |
|            | low addresses
+------------+

On a 64-bit system, there is enough address space that you run out real and virtual memory before the collisions occur.

Also, note that (at least some versions of) Linux are willing to say more memory can be allocated than they can actually support - they over-commit. That is not very good. It means that practical experiments like trial memory allocations may give you a false sense of security.

Most likely, you are best off asking 'is the x MB (GB?) of space left', rather than 'how many MB (GB?) of space is left'. Other people pointed to the /proc file system as a source of information for how much memory is in use. I'm not sure whether it reliably tells you about how much memory is available to grab.

This is a C function to return the amount of free memory on the Raspberry PI. It works by reading the /proc/meminfo. I'm not sure if it works for other systems.

#include <stdio.h>
#include <string.h>
// Return the amount of free memory in kbytes.
// Returns -1 if something went wrong.
int getfreememory()
{
  int returnValue;
  const int BUFFER_SIZE = 1000;
  char buffer[BUFFER_SIZE];
  FILE *fInput;
  int loop;
  int len;
  char ch;
  returnValue = -1;
  fInput = fopen("/proc/meminfo","r");
  if (fInput != NULL)
  {
    while (!feof(fInput))
    {
      fgets(buffer,BUFFER_SIZE-1,fInput);
      if (feof(fInput))
      {
        break;
      }
      buffer[BUFFER_SIZE-1] = 0;
      // Look for serial number
      if (strncmp(buffer,"MemFree:",8)==0)
      {
        // Extract mem free from the line.
        for(loop=0;loop<BUFFER_SIZE;loop++)
        {
          ch = buffer[loop];
          if (ch == ':')
          {
             returnValue = 0;
             continue;
          }
          if (ch == 0)
          {
              break;
          }
          if (returnValue >=0)
          {
             if (ch >='A')
             {
                break;
             }
             if ((ch >='0') && (ch <='9'))
             {
                returnValue = returnValue * 10 + (ch-'0');
             }
          }
        }
        break;
      }
    } 
    fclose(fInput);
  }
  return returnValue;
}

You can check in the /proc namespace the files /proc/<pid>/smaps and /proc/<pid>/maps, where <pid> is the current process id.

Check this blogpost out.

Valgrind's Massif tool supports both stack and heap profiling. You may want to check its source code to see how it does it.

For the heap part, maybe you are hitting a resource limit. Check out this.

You may use Valgrind for stack profiling, but what are you going to do with it ? Stack is not like Heap. You say, you want to do this for debugging purposes. If your program runs fine, then there is no stack problem (related to its size at least).

You may set the stack size for the threads you created and inspect the stack pointer value by looking at the local variable (which must not be optimized-out) addresses. Just do some math by using the initial size, initial stack pointer value and current stack pointer value, you will get some nice numbers. Just do not forget to find out the stack direction first. This may change from platform to platform.

I think if you care this much for heap usage, then your program probably leaks memory. In this case, Valgrind can point you to the right direction. Valgrind

getrlimit with a paramater of RLIMIT_STACK will tell you how much stack space is there in total. With a parameter of RLIMIT_AS you can find out how much virtual memory there is.

For more information look at http://linux.die.net/man/2/getrlimit

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top