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.
Related
This question already has answers here:
Object creation on the stack/heap?
(7 answers)
What and where are the stack and heap?
(31 answers)
Stack, Static, and Heap in C++
(9 answers)
Closed 2 years ago.
I wrote this code and could someone explain how many objects are created in heap and stack? Is myStudent object in heap or stack?
Second question, is main method itself and the things inside of main method stored in stack?
class Student
{
public:
Student()
{
id = 0;
}
private:
int id;
};
Student studentCreator()
{
Student* s = new Student();
return *s;
}
int main()
{
Student myStudent = studentCreator();
return 0;
}
myStudent is on the stack. During the function call you are creating something in the heap and losing its reference.
Here you have myStudent on the stack because that function creates a student on the heap but return it dereferencing it, then you have a memory leak. The main function is stored on the stack by the operating system.
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
}
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.
This question already has answers here:
Can a local variable's memory be accessed outside its scope?
(20 answers)
C++ delete - It deletes my objects but I can still access the data?
(13 answers)
Closed 7 years ago.
Out of fun, I decided to see what gdb would say about this code, which is meant to attempt to use methods of an already destroyed object.
#include <iostream>
class ToDestroy
{
public:
ToDestroy() { }
~ToDestroy() {
std::cout << "Destroyed!" << std::endl;
}
void print() {
std::cout << "Hello!" << std::endl;
}
};
class Good
{
public:
Good() { }
~Good() { }
void setD(ToDestroy* p) {
mD = p;
}
void useD() {
mD->print();
}
private:
ToDestroy* mD;
};
int main() {
Good g;
{
ToDestroy d;
g.setD(&d);
}
g.useD();
return 0;
}
The output is (built with -O0 flag):
Destroyed!
Hello!
Allocating d in the heap and deleting it causes the same behaviour (i.e., no crash).
I assume the memory has not been overwritten and C++ is 'tricked' into using it normally. However, I am surprised about the fact that, when allocating on the heap and deleting, one can use memory not assigned to them.
Can someone provide any more insight about this? Does this mean that when trying to dereference a pointer, if that memory happens to have something 'coherent' for our context the execution would not cause a SEGFAULT despite the memory not having been assigned to us?
A segfault happens when you try to access an address that the OS forbids you to access. This can be because the mem behind the address is not allocated to you process, or because it does not exist or whatever. So you are now trying to access a piece of memory that is still allocated to your process, so no segfault.
Malloc (the one that manages your heap) works with certain buffers to limit the amount of syscalls. So there is uninitialized mem that you can access.
You pass an invalid this pointer to print but it is never dereferenced as print is not virtual nor is it accessing any member.
This question already has answers here:
Is there a reason to call delete in C++ when a program is exiting anyway?
(8 answers)
Closed 8 years ago.
I have the following code:
class A {
public:
virtual void f() {
cout << "1" << endl;
}
};
class B : public A {
public:
void f {
cout << "2" << endl;
}
};
int main() {
A* a = new B();
a->f();
return 0;
}
And my question is: why there is no need to to delete a before return of the main function?
According to my understanding this code will result in a memory leak, am I wrong?
[UPDATE]
I checked the following code using valgrind and it confused me even more. It says there is a memory leak.
There is indeed a memory leak. It lasts from the return of main to the exit of the program, which in this case is very, very short.
"According to my understanding this code will result in a memory leak, am I wrong?"
No you're right, there should be a delete. Though the memory leak usually doesn't matter, since the OS will reclaim all memory allocated from the process after return 0;.