473,809 Members | 2,617 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 4342
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*******@gmai l.com> wrote in news:1116506360 .370454.25030
@f14g2000cwb.go oglegroups.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
30103
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 part of the standard, then just disregard this question. Here's some questions I'm confused about, and if you can add anything else, please do so! Is the stack limited for each program?
17
5054
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
2215
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
3060
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 structure. The compiler obviously allows VLA however it craps out after the above amount of bytes. I was told i was attempting to put everythng on the stack and not the heap. So i was wondering if anyone can maybe clear it up, is that true? would i...
9
3388
by: shine | last post by:
what is the difference between a heap and a stack?
2
13751
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. Best regards.
24
2898
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 are structs, where classes are on the heap... when value types go out of scope the memory is re- allocated, object remain in memory waiting to be cleaned up by the garbage collector, etc, but he responded 'so why not just put say a class on the...
16
4452
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 in RAM/Memory or does it refer to a data structure being used for storing objects. 2. In C++, functions and its local variables go in stack. If local variables that are primitives go in stack, it is OK. But what
53
26414
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 variable? My answer: static variable in function and global variable are allocated in head, and automatic variable is allocated in stack. Right?
9
3175
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 deallocated when it exits. In contrast, malloc() always takes memory in the heap. Now, let's consider the code as follows: int get_buffer() {
0
9603
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10376
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10387
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10120
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7662
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5550
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5689
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4332
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
3015
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.