i read about stack and heap
but i don’t know about this
where is x ( in heap or in stack ) ?
is my code have a memory leak or not ?
struct st
{
int x;
int* y;
};
st* stp;
void func()
{
st* s=new st();
s->x=2;
s->y=new int(5);
stp=s;
}
int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
func();
cout << stp->x << " " << *stp->y <<endl;
delete stp->y;
delete stp;
}
output
2 5
stpis dynamically-allocated, and is therefore on the heap.* Therefore, all its members (includingx) are on the heap.As far as I can see, you don’t have a memory leak.
* Technically, the C++ standard doesn’t talk about stack vs. heap, so it’s up to the compiler where stuff gets allocated. But in practice, it will be stored in a heap-like structure.