473,322 Members | 1,538 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,322 software developers and data experts.

heap vs stack memory

HI,
class A()
{
private:
int i;
char c;
public:
A();
};
void fun(A* a)
{

a = new A(); //allocated on heap(2nd time allocation)
}

int main()
{

A a; // allocated on stack

fun(&a);

}

Can you please tell wheather memory gets allocated 2 times for object
A(one on stack other on heap). Is this a valid code. Does both have
same adress(pointing to memory, even though both are on different
memory).. Atleast tell whats wrong in this code??

Regards

Jul 23 '05 #1
4 4317
Gurikar wrote:
class A()
{
private:
int i;
char c;
public:
A();
};
void fun(A* a)
{

a = new A(); //allocated on heap(2nd time allocation)
}

int main()
{

A a; // allocated on stack

fun(&a);

}

Can you please tell wheather memory gets allocated 2 times for object
A(one on stack other on heap). Is this a valid code. Does both have
same adress(pointing to memory, even though both are on different
memory).. Atleast tell whats wrong in this code??


The only thing that is "wrong" is that the memory allocated in 'fun'
is never freed.

If you change the pointer passed by value into a function to point to
something else inside that function, nothing happens to the object to
which that pointer pointed outside.

In the 'main' function you have 'a'. It has its address, &a. You take
that address an pass to 'fun'. Inside 'fun' there is a pointer to an A,
you called it 'a' to add more confusion to the issue. Fine. The 'a'
inside the 'fun' is initialised with the address of the 'a' in the 'main'
function. Immediately you override the value that came to 'fun' with
another value you obtain by dynamically allocating another A object.

The pointer 'a' inside 'fun' now has some new value, which is lost upon
the function exiting. The object outside 'fun' (the 'a' inside 'main')
never feels a thing.

V
Jul 23 '05 #2
"Gurikar" <ms*******@gmail.com> wrote in news:1116506360.370454.25030
@f14g2000cwb.googlegroups.com:
class A()
{
private:
int i;
char c;
public:
A();
};
void fun(A* a)
{

a = new A(); //allocated on heap(2nd time allocation)
}

int main()
{

A a; // allocated on stack

fun(&a);

}

Can you please tell wheather memory gets allocated 2 times for object
A(one on stack other on heap). Is this a valid code. Does both have
same adress(pointing to memory, even though both are on different
memory).. Atleast tell whats wrong in this code??

This is nearly compilable code (fix the syntax error in the class
declaration and implement the declared constructor). Nonetheless you get
a memory leak when leaving "fun" because the allocated memory is never
freed inside the function.
You have 2 different variables called "a" (let's refer to them as
"main::a" and "fun::a"). When executing the program you get the following
assignments:

fun::a = &main::a; // parameter passing
fun::a = new A(); // inside "fun"; previous assignment is overwritten

After returning from the function call fun::a has been removed but the
memory block where fun::a pointed to is still allocated.
main::a has not been changed and still contains the initial object.

Martin
Jul 23 '05 #3
Gurikar wrote:
HI,
class A()
{
private:
int i;
char c;
public:
A();
};
void fun(A* a)
{

a = new A(); //allocated on heap(2nd time allocation)
}

int main()
{

A a; // allocated on stack

fun(&a);

}

Can you please tell wheather memory gets allocated 2 times for object
A(one on stack other on heap).
No.
Is this a valid code.
Yes.
Does both have same adress(pointing to memory, even though both are on
different memory)..
No.
Atleast tell whats wrong in this code??


Just remember that passing a parameter to a function means that its value
gets copied into the function parameter (unless you pass a reference).
In main, you take the address of a. Then you call fun and pass that address
to it. Fun has a parameter 'a' that this address gets copied into. So fun
now works on a local copy of the pointer value. Any changes to it will only
affect that copy within the function.
The next thing is that you assign to that parameter the return value from
'new A()', which is a pointer to a fresh object of class A. When returning
from the function, the parameter a is destroyed (but not the object it's
pointing to). Since 'a' within foo was just a local copy, nothing has
changed outside the function.
But now you have an object allocated with new, and you lost the only pointer
to it that you had when the function returned. You can never delete the
object anymore.

Jul 23 '05 #4

Thanks for all your answers..

Rolf Magnus wrote:
Gurikar wrote:
HI,
class A()
{
private:
int i;
char c;
public:
A();
};
void fun(A* a)
{

a = new A(); //allocated on heap(2nd time allocation)
}

int main()
{

A a; // allocated on stack

fun(&a);

}

Can you please tell wheather memory gets allocated 2 times for object A(one on stack other on heap).
No.
Is this a valid code.


Yes.
Does both have same adress(pointing to memory, even though both are on different memory)..


No.
Atleast tell whats wrong in this code??


Just remember that passing a parameter to a function means that its

value gets copied into the function parameter (unless you pass a reference). In main, you take the address of a. Then you call fun and pass that address to it. Fun has a parameter 'a' that this address gets copied into. So fun now works on a local copy of the pointer value. Any changes to it will only affect that copy within the function.
The next thing is that you assign to that parameter the return value from 'new A()', which is a pointer to a fresh object of class A. When returning from the function, the parameter a is destroyed (but not the object it's pointing to). Since 'a' within foo was just a local copy, nothing has
changed outside the function.
But now you have an object allocated with new, and you lost the only pointer to it that you had when the function returned. You can never delete the object anymore.


Jul 23 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

14
by: Kevin Grigorenko | last post by:
Hello, I couldn't find an obvious answer to this in the FAQ. My basic question, is: Is there any difference in allocating on the heap versus the stack? If heap or stack implementation is not...
17
by: Jonas Rundberg | last post by:
Hi I just started with c++ and I'm a little bit confused where stuff go... Assume we have a class: class test { private: int arr; };
9
by: gold | last post by:
Hello all, I want know abt wht kind of datastructures using both C & C++ internally. Some were said heap, others said tree anyone can explain brief?
22
by: bitshadow | last post by:
using the following code, i was able to have my compiler seg fault on me when i gave the argument as anythng greater than 20,832,000bytes. In the case of the struct its 868 instances of said...
9
by: shine | last post by:
what is the difference between a heap and a stack?
2
by: Ma Xiaoming | last post by:
Dear ladies and gentlemen, I don't understand what the difference between the Heap and the Stack is. Could you please explain the difference between the both for me? Thank you very much. ...
24
by: arcticool | last post by:
I had an interview today and I got destroyed :( The question was why have a stack and a heap? I could answer all the practical stuff like value types live on the stack, enums are on the stack, as...
16
by: sarathy | last post by:
Hi all, I need a few clarifications regarding memory allocaion in C++. I apologize for the lengthy explanation. 1. In C++, Objects are allocated in heap. What does heap refer to? Is it an area...
53
by: fdmfdmfdm | last post by:
This is an interview question and I gave out my answer here, could you please check for me? Q. What are the memory allocation for static variable in a function, an automatic variable and global...
9
by: Roman Mashak | last post by:
Hello, I'm confused about heap and stack memories management in C language. Most books explain that local stack variables for each function are automatically allocated when function starts and...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.