Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can C++ memory leaks negatively affect CPU usage?

I have a C++ program that has a pretty terrible memory leak, about 4MB / second. I know where it's coming from and can fix it, but that's not my main problem. My program is taking up a very large amount of CPU usage and it isn't running as fast as I want it to. I have two different threads in the program. One by itself takes ~50% CPU, which is fine, and the other by itself takes ~15% CPU, which is fine. Together however CPU usage is 100% and the program cannot run as fast as it needs to.

Can a memory leak by itself cause a problem like this? I know the program will eventually crash due to the leaked memory, but does a memory leak immediately lead to a slower program? By immediately I mean the program is too slow at the very start, not just when the memory footprint is huge.

Thanks!

like image 701
Dan Avatar asked Jun 03 '10 16:06

Dan


People also ask

Does memory leak affect CPU usage?

Note: Applications with memory leaks can cause the CPU to work excessively. As a system's available RAM decreases, the system relies increasingly on the pagefile. The more heavily the pagefile is used, the more time is spent swapping pages between physical and virtual memory.

Does memory leak affect performance?

Memory leaks are a class of bugs where the application fails to release memory when no longer needed. Over time, memory leaks affect the performance of both the particular application as well as the operating system. A large leak might result in unacceptable response times due to excessive paging.

What happens when memory leak in C?

In other words, leaks mean that dynamically-allocated memory cannot be released back to the operating system because the program no longer contains pointers that can access it. You've lost control of that piece of memory regardless of size and can no longer access it or free it.

How are memory leaks harmful?

A memory leak reduces the performance of the computer by reducing the amount of available memory. Eventually, in the worst case, too much of the available memory may become allocated and all or part of the system or device stops working correctly, the application fails, or the system slows down vastly due to thrashing.


2 Answers

Regardless of whether or not your memory leak is causing the problem it needs to be fixed. Once you fix the memory leak see if you're still having the problem. You should be able to answer your own question at that point.

like image 97
Ben Burnett Avatar answered Oct 16 '22 07:10

Ben Burnett


Allocations in general can be slow and it sounds like you're doing a lot of them here. After fixing your leak, you will want to consider a pooled memory implementation to avoid thrashing your heap so much, especially in a multi-threaded environment.

like image 4
bshields Avatar answered Oct 16 '22 07:10

bshields