473,698 Members | 2,068 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

pointer and reference confuse

Hi All

simple question:

1.============= =============== ========

{
int* p_1 = new int();
};
//will p1 leak?

2.============= =============== ========
class MyClass
{

public:
MyClass(){
p_2 = new int();
}
private:
int* p_2;
};

MyClass* mc_ = new MyClass();
delete mc_;
//will p_2 leak?
3.============= =============== ========

int* p_3 = new int();

{
int& r_1 = *p_3
};

//will p_3 hang?

4.============= =============== ========

I always confuse on these "will hang,will not hang...,will leak ,will not
leak"
, any knack?
thank you very much.
key9

Mar 2 '06 #1
4 1674
key9 <ia*****@126.co m> wrote:
{
int* p_1 = new int();
};
//will p1 leak?
Yes, because there is no way to call 'delete' with the pointer value
that the above 'new' gave you.
class MyClass
{

public:
MyClass(){
p_2 = new int();
} private:
int* p_2;
}; MyClass* mc_ = new MyClass();
delete mc_;
//will p_2 leak?
Yes, because again, you are not calling 'delete' for all pointers
that where returned by 'new'. Remember this rule:

a) Every call to 'new' needs a matching call to 'delete'and
b) every call to 'new[]' needs matching call to 'delete[]'

In the case above, you are missing the matching 'delete' for 'p_2'.
int* p_3 = new int();

{
int& r_1 = *p_3
};
//will p_3 hang?


Hang? The code will work, but again, you must "delete p_3;" after
you are done using it. As it is there, you have a memory leak.

hth
--
jb

(reply address in rot13, unscramble first)
Mar 2 '06 #2

key9 wrote:
Hi All

simple question:

1.============= =============== ========

{
int* p_1 = new int();
};
//will p1 leak?
Yes. To avoid leaks, you must match every new with delete and every new
[] with delete []. p_1 is the only pointer pointing to the dynamically
allocated memory. When p_1 goes out of scope and is destroyed you can't
delete the memory because you have no pointer to pass to delete.
2.============= =============== ========
class MyClass
{

public:
MyClass(){
p_2 = new int();
}
private:
int* p_2;
};

MyClass* mc_ = new MyClass();
delete mc_;
//will p_2 leak?
Yes. There is no delete to match the new that was used to assign a
value to p_2. And when mc_ is destroyed, it's member p_2 is destroyed
and you have exactly the same problem as before. Some memory has been
allocated but you no longer have any pointers that point to it so you
can't deallocate the memory.

The destructor of MyClass should deallocate the memory. Bear in mind
that you will then need to write (or disable) the copy contructor and
assignment operator.
3.============= =============== ========

int* p_3 = new int();

{
int& r_1 = *p_3
};

//will p_3 hang?
p_3 is still in scope here so you can delete p_3; and you have no
problem. r_1 has already gone out of scope so is irrelevant. Were you
thinking of this?

int pi = new int;
int& ri = *pi;
delete pi;
// The int that ri refers to has been destroyed.
// ri is now a dangling reference.
4.============= =============== ========

I always confuse on these "will hang,will not hang...,will leak ,will not
leak"
, any knack?


Read the FAQ
http://www.parashift.com/c++-faq-lit...tore-mgmt.html

Once you've read that, make sure you always use standard library
classes and RAII techniques so you never have this sort of problem in
real code. new and delete should appear rarely in you code. When they
do appear, the memory should be managed by a class designed for the
purpose.

Gavin Deane

Mar 2 '06 #3
key9 wrote:
Hi All

simple question:

1.============= =============== ========

{
int* p_1 = new int();
};
//will p1 leak?
Is there a matching delete for the new p_1?
2.============= =============== ========
class MyClass
{

public:
MyClass(){
p_2 = new int();
}
private:
int* p_2;
};

MyClass* mc_ = new MyClass();
delete mc_;
//will p_2 leak?
Again, is there a matching delete for the new p_2?
3.============= =============== ========

int* p_3 = new int();

{
int& r_1 = *p_3
};

//will p_3 hang?
hang is not defined by the standard.
4.============= =============== ========

I always confuse on these "will hang,will not hang...,will leak ,will not
leak"
, any knack?


Is this homework?

The knack is to know what happens when a scope *is* left. Do you
understand the construction and destruction process, and how scope
affects that?

You also need to know when a scope *can* be left, and it's not always at
the end of it.

Each call to new has to have 1 and only one matching call to delete.
Similarly for new[] and delete[].

There are techniques which are used to minimise the problems of
determining when to deallocate a resource (such as memory allocated with
new, by calling delete). This is called RAII (Resource Acquisition Is
Initilisation). It is leveraged by the use of resource allocation and
deallocation with the lifetime of an object. I.e., an object manages
the resource by obtaining the resource in the constructor, and releasing
the resource in the destructor.

Aggressive use of RAII techniques makes for robust code.

Ben Pope
--
I'm not just a number. To many, I'm known as a string...
Mar 2 '06 #4
Thanks a lot.
Mar 2 '06 #5

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

Similar topics

38
4618
by: Radde | last post by:
HI all, Whats the difference b/w pass by ref and pass by pointer in C++ when ur passing objects as args.. Cheers..
9
2995
by: Sandy | last post by:
Hi, In one of my interview I was asked a question, whether using pointers for argument is efficient then reference or not. i.e. void fun(Complex *p) void fun(Complex &ref) can somebody tell me which one will be more efficient and why? as far as i know both must be same, because i read somewhere that internally
27
2913
by: Riaan Cillié | last post by:
Hi I'm trying to learn C, but I am struggling with using scanf and a struct. I want to define a structure and declare a variable of that type in int main. This has to be passed to a function and its values have to read and returned from this function. How do you use gets() for this? I just can't figure it out. Here is a bit of code
79
125218
by: syntax | last post by:
what is the size of a pointer? suppose i am writing, datatype *ptr; sizeof(ptr); now what does this sizeof(ptr) will give? will it give the size of the
40
1851
by: Foobarius Frobinium | last post by:
Please review this guide for clarity, accuracy, etc. so I can hopefully compile a very good tutorial on how to use pointers in C, including advanced topics, that is easy to follow and exposes the details. http://thelinuxlink.net/~fingolfin/pointer-guide/ My e-mail address is fake. To really contact me, send mail to: fingolfinJOHNLENNONSPENIS@thelinuxlink.net, subtracting the blatant anti-spam component.
17
2587
by: Divick | last post by:
Hi, I am designing an API and the problem that I have is more of a design issue. In my API say I have a class A and B, as shown below class A{ public: void doSomethingWithB( B * b) { //do something with b //possibly store in a list
14
2409
by: key9 | last post by:
Hi All On coding , I think I need some basic help about how to write member function . I've readed the FAQ, but I am still confuse about it when coding(reference / pointer /instance) , so I think I need some "template". Sorry for my coding experience in c++
8
1760
by: joel.winteregg | last post by:
Hi all, I "learnt" C++ a few years ago and then i have been using C for a couple of month and i'm now trying to get back to the ++ world (but with some troubles...). I have some problem to understand why a "new" return a pointer and not a reference. Here are explanations: /* to get my object in heap */
6
2519
by: worlman385 | last post by:
For pointer and non-pointer initialization of an object like MyCar mycar; MyCar* mycar = new MyCar(); I heard from other people saying if object i create must live outside scape, then I use pointer version, else if only use object for a limited scope, then use non-pointer version. Does limited scope means the object is only used in the same function
0
8673
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9156
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9021
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...
0
8860
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...
0
7716
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5860
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4614
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2327
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
1998
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.