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.
Related
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.
This question already has answers here:
When to use "delete"?
(5 answers)
When to use new and delete
(4 answers)
Calling delete on variable allocated on the stack
(12 answers)
Do I have to delete struct pointer manually in C++?
(4 answers)
Closed 3 years ago.
Let's say I have a struct defined as so:
struct Barre {
int startString;
int endString;
Barre() { startString = endString = -1; }
Barre(int s, int e) : startString(s), endString(e) {}
bool exists() { return startString > -1; }
};
I will create an instance of this struct like this, for example:
Barre b = Barre(2, 4);
Let's say I insert this into a std::map<int, Barre> which is a member of a class, with a key of, for example, 3.
If I then create another Barre as above and overwrite the value of the map at key 3 with this new instance of the Barre struct, do I need to explicitly delete the old Barre object that I'm overwriting to prevent memory leaks? Or does it not persist once it is no longer stored in a map in this way?
Thanks for any help.
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.
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 way to statically-initialize a dynamically-allocated array in C++?
(6 answers)
Closed 9 years ago.
In C++, I have a class CMyObject as follows, where CData is another class name:
Class CMyObject
{
CMyObject(CData& Data): m_Data(Data) {};
virtual ~CMyObject(void);
private:
const CData& m_Data;
}
When allocate one CMyObject instance, I can do as follows:
P = new CMyObject(MyData);
However, if I want to create an array of CMyObject, then can I do as follows?
P = new CMyObject(MyData)[10];
You can use an initialization list (I used 4 to save some typing, but you get the idea):
CMyObject* P = new CMyObject[4]{MyData, MyData, MyData, MyData};
But better still, use an std::vector:
std::vector<CMyObject> P(10, MyData);