While you can't check memory usage directly from within C++, there are several tools and techniques you can use to monitor how much memory your program is using.
The simplest way on Windows is to use Task Manager:
On Mac, you can use Activity Monitor:
If you're using Visual Studio:
Here's a simple program that uses different amounts of memory. Try running it and watching the memory usage in Task Manager:
#include <iostream>
#include <string>
using namespace std;
int main() {
cout << "Press Enter to continue each"
" step...\n\n";
string input;
getline(cin, input);
// Create some variables that use memory
int32_t Numbers[10000];
cout << "Created array of 10000 integers\n";
getline(cin, input);
// Create more variables
int32_t MoreNumbers[100000];
cout << "Created array of 100000 integers\n";
getline(cin, input);
cout << "Program ending...";
}
The program pauses between allocations so you can watch the memory usage increase in Task Manager. Remember that the total memory used will be more than just our variables - the program itself needs some memory to run!
While these tools can help you track memory usage, the best way to manage memory is to think about it while writing your code. Use appropriate types for your data, and avoid creating unnecessary variables or really large arrays unless you need them.
Answers to questions are automatically generated and may not have been reviewed.
Explore how C++ programs store and manage numbers in computer memory, including integer and floating-point types, memory allocation, and overflow handling.