user3481478
user3481478

Reputation: 387

No change in RAM usage when running c++ program

I wrote a simple program trying to see change in memory but there was a none. A straight horizontal line around 20% comes always, whether I run the code or not.

#include<iostream>
using namespace std;
int main()
{
       int *m;
       int i;
       cin>>i;
       m = new int[i];
}

Shouldnt memory be allocated for any value of i? And a change in Memory free be shown?

Upvotes: 1

Views: 1115

Answers (3)

Jason
Jason

Reputation: 3917

A number of things might be happening...

  • compiler the compiler may be optimizing the memory allocation out (since nothing is actually done with it)
  • operating system the memory may not be allocated by the operating system since the pages aren't written to
  • sampling the resource usage may not show up on your system monitor since your program exits immediately after allocating the memory

So, to eliminate these potential causes you could write something like this...

#include <iostream>

int main(int argc, char* argv[]) {

  int x,y;

  std::cin >> x;

  int* m = new int[x];

  for (int i = 0; i < x; i++)
    m[i] = i;

  std::cin >> y;

  std::cout << m[y] << std::endl;

  return 0;
}

Then, you should be able to check memory usage before you enter the y value. I'm not sure what operating system you're using, but you should see the image size and the resident memory of the program increase roughly by 4x bytes.

Upvotes: 2

Ari0nhh
Ari0nhh

Reputation: 5920

There could be plenty of reasons why this is happening:

  1. Compiler optimization - if you turn compiler optimizations on, it could determine that your m pointer is never used, so it will simply delete new[] operator call;
  2. Operating system optimization - heap allocation is OS Memory Manager business. It could allocate memory only on the first memory usage. For example Windows API HeapAlloc method behaves that way;
  3. Your tool limitations - memory allocation/deallocation could be too fast for it to catch (basing on your example);
  4. Memory allocation failure - if your i value is too big, there is a possibility that heap manager will be unable to find continuous memory block of such size, so new operator will raise bad_alloc exception and your program will be terminated.

Upvotes: 3

Zdeněk Šimůnek
Zdeněk Šimůnek

Reputation: 1

You allocated memory for maximum size of a int. That is 4 bytes. Now lets say that your RAM has 8 GB for example. 4 bytes are about 0.00000005% of 8 GB RAM.

Upvotes: -1

Related Questions