Will delete[] with void* cause memory leak? [duplicate] - c++

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Is it safe to delete a void pointer?
Will the following code cause memory leak?
void *ptr = new long [10];
delete[] ptr; // note: ptr is a void*
[EDIT]
The code above will generate a warning message during compiling to specify it "undefined".
I ask this cause I'm wondering how does C++ handle memory ranges when delete[] is called.
I should change my question to make it more specified.
Will the following code cause memory leak?
char *ptr = (char *)(new long [10]);
delete[] ptr; // note: ptr is a char*

No. Leaving delete[] out will cause a leak. BTW, it should be long* ptr. I don't think the delete[] will even compile with a void* argument.

I tried the following program (slight modification of this example):
#include <iostream>
#include <new>
using namespace std;
struct myclass {
myclass() {cout <<"myclass constructed\n";}
~myclass() {cout <<"myclass destroyed\n";}
};
int main () {
void * pt = new myclass[3];
delete[] pt;
return 0;
}
using g++ and got the following compilation warning:
leaky.cpp: In function ‘int main()’:
leaky.cpp:13: warning: deleting ‘void*’ is undefined
And when you run it...fail! The process dies (invalid pointer) when you attempt to delete that pointer.

Related

Memory deallocation with deleting smart pointer does not work [duplicate]

This question already has answers here:
Memory consumption after new then delete
(3 answers)
Closed 3 years ago.
I declare and assign vector pointer with shared pointer of class that has a big-size array pointer.
From deleting the vector pointer, I expect to free the memory from the big array. My question is that why the memory is NOT deallocated at the right moment after 'delete vec' before 'return 0'. From debugging mode, you can see it in the window task manager. Please let me know why 'delete vec' does not work as I expected.
class test
{
public:
test() { A = new double[500000000]; }
~test() { delete[] A; }
double *A;
};
int main()
{
vector<shared_ptr<test>> *vec =new vector<shared_ptr<test>>();
vec->push_back(shared_ptr<test>(new test()));
vec->push_back(shared_ptr<test>(new test()));
vec->push_back(shared_ptr<test>(new test()));
delete vec;
return 0;
}
I tested your code and there is no problem when deleting ptr.

Heap crash when overloading new and delete [duplicate]

This question already has answers here:
How could pairing new[] with delete possibly lead to memory leak only?
(10 answers)
Closed 6 years ago.
I am getting heap crash in delete call of overloaded delete. Please help me in resolving this issue.
class number {
int *series;
public:
void* operator new(size_t size){
number *n = ::new number;
n->series = new int[size];
printf("new %p %p\n", n, n->series);
return n;
}
void operator delete(void *ptr) {
number *n = (number*)ptr;
printf("delete %p %p\n", n, n->series);
delete (int*)n->series;// why crash here?
::delete n;
}
};
int main() {
number *n= new number;
delete n;
return 0;
}
You allocated series as an array, using new int[size]. So you must free it as one: delete [] n->series.
(I'm not sure why to have the cast there, but it's a bad idea. If you tell the compiler to ignore your errors it just makes things harder.)

Should i use delete[] in a function? [duplicate]

This question already has answers here:
Is not calling delete on a dynamically allocated object always a memory leak?
(6 answers)
Closed 6 years ago.
void work() {
int *p;
p=new int[10];
//some code....
}
I have a short question that in the work function, should i use delete[] operator? since when work function is over, p will be destroyed, which is wrong or right ? (My English is bad, i am sorry).
This will work as long as the code throws no exceptions...
void work() {
int *p;
p=new int[10];
//some code....
delete [] p;
}
This is better (but difficult to maintain):
void work1() {
int *p;
p=new int[10];
try {
//some code....
} catch(...) {
delete [] p;
}
delete [] p;
}
This is much better...
void work2()
{
auto p = std::unique_ptr<int[]>(new int[10]);
// some code...
// memory is automatically deleted
}
And this is how you should do it...
void work3()
{
auto v = std::vector<int>(10);
// some code...
}
You're right, if you have no reference to p outside of the function, e.g. a global variable, then you need to call delete [] p right inside of the function, otherwise the reference to the allocated memory you want to free is lost.
Yes, if integers are allocated using new int[10], you need to clean up using delete[], since it is an array.
Yes, you need to release the memory from new.
Alternatively with C++11, you can use smart pointer:
void work() {
std::unique_ptr<int[]> p{ new int[10] };
//some code....
// RAII will delete[] magically here
}
Alternatively, if you are using just few integers (10 in your case), that are known in compile time, you can do "normal" or static array. e.g.
void work() {
/* static */ int p[10];
//some code....
}
Alternatively, use std::vector:
void work() {
std::vector<int> p{10};
//some code....
// RAII will delete[] magically here
}
Alternatively, with C++11 if array size is known in compile time, use std::array:
void work() {
std::array<int,10> p;
//some code....
// RAII will delete[] magically here
}

dangling pointer is still accessing the memory value [duplicate]

This question already has answers here:
What does delete command really do for memory, for pointers in C++? [duplicate]
(6 answers)
Closed 6 years ago.
I am pretty new to this concept and I am confused that if a dangling pointer is a pointer which points to a memory location which points to memory which has been freed or deleted then in this case why it is still able to call the function test()
#include <stdio.h>
#include <iostream>
#include <stdlib.h>
using namespace std;
class MyClass{
public:
void test(){
cout<< "just checking"<<endl;
}
};
int main(int argc, char **argv)
{
MyClass *p ( new MyClass());;
MyClass *q = p;
delete p;
q->test();
p = NULL;
q->test();
return 0;
}
Any help would be appreciated.
Delete runs the destructor of the class, and marks the memory as freed. If the destructor doesn't do anything too destructive, and if the memory has not yet been reallocated for some other purpose, then the object turns into what is basically a zombie: it looks vaguely like one of the living, but is really preparing to eat your brain.
Don't let your brain get eaten.

Valgrind does not report memory leak on "delete array"

After implementing the C++ code below, I ran valgrind --leak-check=full in order to check if there was any memory leak. The result was 0 bytes were in use at exit and no leaks are possible.
However, later I discovered that I've forgotten to use delete[] x instead of just delete x inside the destructor.
I searched for some explanations (for instance: delete vs delete[] operators in C++), and everything I read said that using delete without [] can cause memory leak, since it calls just the destructor for the first object in the array.
I changed the code to delete[] and the valgrind output was the same (as expected). But now I'm confused: "Is there a problem with valgrind, or does delete really works fine for arrays even without the operator []?"
#include <iostream>
#include <string.h>
using namespace std;
class Foo {
private: char *x;
public:
Foo(const char* px) {
this->x = new char[strlen(px)+1];
strcpy(this->x, px);
}
~Foo() {
delete x;
}
void printInfo() { cout << "x: " << x << endl; }
};
int main() {
Foo *objfoo = new Foo("ABC123");
objfoo->printInfo();
delete objfoo;
return 0;
}
using delete without [] causes memory leak.
No, it causes Undefined Behavior.
Your program where you allocate using new [] and deallocate using delete has Undefined Behavior. Actually, you are lucky(rather unlucky) it doesn't show some weird behavior.
As a side note, You also need to follow the Rule of Three for your class. Currently, you don't do so and are calling for trouble in near future.
The main difference between delete and delete[] is not about memory deallocation, but about destructor calls.
While formally undefined behavior, in practice it will more or less work... except that delete will only call the destructor of the first item.
As a side note, you may get an issue:
#include <iostream>
struct A{
~A() { std::cout << "destructor\n"; }
};
int main() {
A* a = new A[10];
delete a;
}
a bit like:
*** glibc detected *** ./prog: munmap_chunk(): invalid pointer: 0x093fe00c ***
======= Backtrace: =========
/lib/libc.so.6[0xb759dfd4]
/lib/libc.so.6[0xb759ef89]
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/libstdc++.so.6(_ZdlPv+0x21)[0xb77602d1]
./prog(__gxx_personality_v0+0x18f)[0x8048763]
./prog(__gxx_personality_v0+0x4d)[0x8048621]
======= Memory map: ========
See it at ideone.