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.
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 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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With