Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ static array leading to memory leak?

Lets say I have something like...

void foo()
{
    char c[100];
    printf("this function does nothing useful");
}

When foo is called, it creates the array on the stack, and when it goes out of scope, is the memory deallocated automatically? Or is c destroyed, but the memory remains allocated, with no way to access it/get it back except restarting the computer?

like image 403
MDonovin Avatar asked May 03 '10 15:05

MDonovin


People also ask

What causes memory leak C?

In computer science, a memory leak is a type of resource leak that occurs when a computer program incorrectly manages memory allocations in such a way that memory which is no longer needed is not released. A memory leak may also happen when an object is stored in memory but cannot be accessed by the running code.

Do vectors cause memory leaks?

std::vector does not cause memory leaks, careless programmers do. You should also include an example that actually exhibits the behavior you are experiencing, including calls to the CRT debug API. There's a good possibility that you're incorrectly interpreting the leaks based on when they are reported.

Do memory leaks cause permanent damage?

Memory leaks don't result in physical or permanent damage. Since it's a software issue, it will slow down the applications or even your whole system. However, a program taking up a lot of RAM space doesn't always mean its memory is leaking somewhere. The program you're using may really need that much space.


1 Answers

is the memory deallocated automatically?

Yes. And the destructors will be called too, in case you wonder. This is why they're in the automatic storage class.

(Actually for most architectures the program will only call that 100 destructors (if any), then shift the stack pointer backward by 100*sizeof(T) bytes as "deallocation".)

like image 157
kennytm Avatar answered Sep 30 '22 01:09

kennytm