where is struct field that created by new (heap or stack)?

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

Answers


stp is dynamically-allocated, and is therefore on the heap.* Therefore, all its members (including x) 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.


Need Your Help

increment variable in awk based on two columns

linux shell variables awk count

I am writing an awk script that parses a CSV file, compares one column containing date, and another column containing activity type, and then prints the count of a particular activity.

Catching SQLException instead of Spring DataIntegrityViolationException in unit testing

java sql spring unit-testing

I am writing unit test to test failed update in DB by using stored procedure. I have a stored procedure which update one of the table. From test I am sending incorrect data(i.e. data that violate

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.