No need to delete dynamic data? [duplicate] - c++

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;.

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.

Accessing pointers after deletion [duplicate]

This question already has answers here:
What happens to the pointer itself after delete? [duplicate]
(3 answers)
Closed 3 years ago.
I have a code snippet like below. I have created some Dynamic memory allocation for my Something class and then deleted them.
The code print wrong data which I expect but why ->show does not crash?
In what case/how ->show will cause crash?
Is it possible to overwrite the same memory location of i, ii, iii with some other object?
I am trying to understand why after delete which frees up the memory location to be written with something else still have information about ->show!
#include <iostream>
#include <vector>
class Something
{
public:
Something(int i) : i(i)
{
std::cout << "+" << i << std::endl;
}
~Something()
{
std::cout << "~" << i << std::endl;
}
void show()
{
std::cout << i << std::endl;
}
private:
int i;
};
int main()
{
std::vector<Something *> somethings;
Something *i = new Something(1);
Something *ii = new Something(2);
Something *iii = new Something(3);
somethings.push_back(i);
somethings.push_back(ii);
somethings.push_back(iii);
delete i;
delete ii;
delete iii;
std::vector<Something *>::iterator n;
for(n = somethings.begin(); n != somethings.end(); ++n)
{
(*n)->show(); // In what case this line would crash?
}
return 0;
}
The code print wrong data which I expect but why ->show does not crash?
Why do you simultaneously expect the data to be wrong, but also that it would crash?
The behaviour of indirecting through an invalid pointer is undefined. It is not reasonable to expect the data to be correct, nor to expect the data to be wrong, nor to expect that it should crash, nor to expect that it shouldn't crash - in particular.
In what case/how ->show will cause crash?
There is no situation where the C++ language specifies the program to crash. Crashing is a detail of the particular implementation of C++.
For example, a Linux system will typically force the process to crash due to "segmentation fault" if you attempt to write into a memory area that is marked read-only, or attempt to access an unmapped area of memory.
There is no direct way in standard C++ to create memory mappings: The language implementation takes care of mapping the memory for objects that you create.
Here is an example of a program that demonstrably crashes on a particular system:
int main() {
int* i = nullptr;
*i = 42;
}
But C++ does not guarantee that it crashes.
Is it possible to overwrite the same memory location of i, ii, iii with some other object?
The behaviour is undefined. Anything is possible as far as the language is concerned.
Remember, a pointer stores an integer memory address. On a call to delete, the dynamic memory will be deallocated but the pointer will still store the memory address. If we nulled the pointer, then program would crash.
See this question: What happens to the pointer itself after delete?

The pointer to memory location to the object has been deleted in program but still provides the correct answer and not garbage value [duplicate]

This question already has answers here:
C++ delete - It deletes my objects but I can still access the data?
(13 answers)
Closed 4 years ago.
The pointer *sbi memory is freed using the delete operator but still the code executes correctly without providing garbage value. is the constructor re-initializing or is the a fault in code/
#include <iostream>
using namespace std;
class bank
{
private:
int balance;
public:
bank();
void dep(int x);
void with();
~bank();
};
int main()
{
bank *sbi;
sbi = new bank;
sbi->dep(50000);
delete sbi; /// problem is in this section of code
sbi->with();
return 0;
}
bank :: bank()
{
balance=0;
}
void bank::dep(int x)
{
balance=x;
}
void bank::with()
{
cout<<balance<<endl;
}
bank::~bank()
{
cout<<"destroy"<<endl;
}
Freeing a memory location does not automatically overwrite it with garbage. By coincidence, that value stored in balance is still the same.

C++ after delete

I am new to C++ and I was wondering why...
#include <iostream>
using namespace std;
class myClass{
public:
void myMethod(){
cout << "It works!" << endl;
}
myClass(){
cout << "myClass is constructed!" << endl;
}
~myClass(){
cout << "This class is destructed!" << endl;
}
};
int main()
{
myClass c;
c.myMethod();
myClass *e = &c;
delete e;
cout << "This is from main" << endl;
return 0;
}
So up there is the code. and the output is
myClass is constructed!
It works!
This class is destructed!
I am wondering where did the "This is from main" output go away.. does C++ doesn't execute codes after delete keyword?
You can only delete objects that have been created with new.
What you're doing is UB, by the means of double deletion.
By the way, while in this case your program stopped execution right after the statement that had UB, it doesn't necessarily have to happen this way because
However, if any such execution contains an undefined operation, this
International Standard places no requirement on the implementation
executing that program with that input (not even with regard to
operations preceding the first undefined operation).
You have undefined behavior. You are not allowed to delete something that was not allocated with new. In doing so you have undefined behavior and your program is allowed to do what it wants.
Most likely you should have received some sort of hard fault that stopped the program from running.
You caused undefined behavior by deleting something that was not newed. You don't need to delete stuff that just points at some general location. You only delete that which you created by calling new (not placement new!).
Perhaps it is good idea for you to read about stack and heap memory.
You must free only when you malloc (or other variations such as calloc).
For example:
char *c = (char *)malloc(255);
...
free(c)
You must delete only if you use new.
MyClass *e = new MyClass()
...
delete e
You must delete[] only if you use new[]
char *data = new char[20]
...
delete[] data
Now, if you do something like this:
...
{
int x;
x = 3;
}
x will be destroyed after the bracers because it is out of scope. This puts x on the stack. However, if you use malloc, new, or delete, the variable itself can be lost if you are not careful, but the memory is allocated. This is memory leak.
What you have is even more dangerous. You are deleting something which was not allocated. The behavior is not defined. With time and patience, a skilled hacker can study the behavior and may be able to break into your system and acquire same privileges as your program.

Accessing an already destroyed object does not cause segfault [duplicate]

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.