Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this a memory leak?

char *pointer1;
char *pointer2;

pointer1 = new char[256];
pointer2 = pointer1;

delete [] pointer1;

In other words, do I have to do delete [] pointer2 as well?

Thanks!

like image 391
Ben Avatar asked May 17 '10 21:05

Ben


People also ask

How do I know if I have a memory leak?

The system can have a myriad of symptoms that point to a leak, though: decreased performance, a slowdown plus the inability to open additional programs, or it may freeze up completely.

What is considered a memory leak?

DEFINITION A memory leak is the gradual deterioration of system performance that occurs over time as the result of the fragmentation of a computer's RAM due to poorly designed or programmed applications that fail to free up memory segments when they are no longer needed.

What does a memory leak do?

Memory leak occurs when programmers create a memory in heap and forget to delete it. The consequences of memory leak is that it reduces the performance of the computer by reducing the amount of available memory.

Are memory leaks real?

In computer science, a memory leak is a type of resource leak that occurs when a computer program incorrectly manages memory allocations in 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.


2 Answers

Nope, that code is fine and won't leak memory.

You only have to use delete[] once because you've only used one new to allocate an area for memory, even though there are two pointers to that same memory.

like image 74
Nilbert Avatar answered Sep 25 '22 21:09

Nilbert


A simple rule: you need as many deletes as there are news. Even better, use something like a smart pointer or a container to take care of it for you.

And another minor point: pointer2 is becoming a "dangling pointer" once you call delete on pointer1.

like image 24
Nemanja Trifunovic Avatar answered Sep 25 '22 21:09

Nemanja Trifunovic