This is a mini test. The memory used by this C++ program increases from 1KB to 10MB while writing a string to a file. It seems that ofstream
didn’t release its memory after append.
In theory, std::ofstream
should write data directly to a file instead of writing to memory. However, the program’s memory usage may continue to increase.
Is this normal?
<code>int main() {
std::string test = "this is a test string xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
for (int i = 0; i < 100 * 1000; i++) {
std::ofstream oss("/opt/agent/log/log.txt", std::iostream::app);
if (oss.is_open()) {
oss << test;
oss.close();
}
usleep(1 * 1000);
}
return 0;
}
</code>
<code>int main() {
std::string test = "this is a test string xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
for (int i = 0; i < 100 * 1000; i++) {
std::ofstream oss("/opt/agent/log/log.txt", std::iostream::app);
if (oss.is_open()) {
oss << test;
oss.close();
}
usleep(1 * 1000);
}
return 0;
}
</code>
int main() {
std::string test = "this is a test string xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
for (int i = 0; i < 100 * 1000; i++) {
std::ofstream oss("/opt/agent/log/log.txt", std::iostream::app);
if (oss.is_open()) {
oss << test;
oss.close();
}
usleep(1 * 1000);
}
return 0;
}
my program produces larger log so this is not acceptable.
More info:
- the memory is measured by register the program as a service, so we can get the status using
systemctl status xxx.service
New contributor
Geoffrey is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
12