Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this code not result in a memory leak? [duplicate]

I checked the following code in C++ with valgrind with --leak-check=full and it says no memory leak. Why is that?

char *p = new char[256]; delete p; 

new[] should be matched by delete[] as far as I know.

like image 392
Dan Lincan Avatar asked Sep 27 '13 07:09

Dan Lincan


People also ask

What causes memory leaks in code?

In general, a Java memory leak happens when an application unintentionally (due to logical errors in code) holds on to object references that are no longer required. These unintentional object references prevent the built-in Java garbage collection mechanism from freeing up the memory consumed by these objects.

How do I know if my code has a memory leak?

How can I detect a memory leak? The simplest way to detect a memory leak is also the way you're most likely to find one: running out of memory. That's also the worst way to discover a leak! Before you run out of memory and crash your application, you're likely to notice your system slowing down.

What is a memory leak and how would you avoid it?

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.

Which of the following actions can cause memory leak?

Causes of Memory Leaks Using Unwanted Object Reference: These are the object references that are no longer needed. The garbage collector is failed to reclaim the memory because another object still refers to that unwanted object. Using Long-live Static Objects: Using static objects also leads to a memory leak.


2 Answers

Although it's undefined behaviour as @KillianDS says, the difference probably relates to the fact that both delete and delete[] free the underlying memory. The point of delete[] is that the destructors for each object in the array are called before the memory is freed. Since char is a POD and doesn't have a destructor, there isn't any effective difference between the two in this case.

You definitely shouldn't rely on it, however.

like image 134
Jonathan Potter Avatar answered Sep 21 '22 07:09

Jonathan Potter


delete and delete[] will be equal only if the p points to basic data types, such as char or int.

If p points to an object array, the result will be different. Try the code below:

class T { public:     T() { cout << "constructor" << endl; }     ~T() { cout << "destructor" << endl; } };  int main() {     const int NUM = 3;     T* p1 = new T[NUM];      cout << p1 << endl;     //  delete[] p1;     delete p1;      T* p2 = new T[NUM];     cout << p2 << endl;     delete[] p2; } 

By using delete[] all the destructors of T in the array will be invoked. By using delete only p[0]'s destructor will be invoked.

like image 38
eleforest Avatar answered Sep 21 '22 07:09

eleforest