473,246 Members | 3,228 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,246 software developers and data experts.

various way to delete pointer to pointer

i just search for a while in c++ groups but cannot find good answer.

i have code like this:

int **ptr;
ptr = new char *[2];

ptr[0] = new int(5);
ptr[1] = new int(16);

i know we can delete ptr like this:

for (int i = 0; i <2; i++)
delete ptr[i];
delete ptr;

But can i delete like this? :

delete ptr;
for (int i = 0; i <2; i++)
delete ptr[i];

or

can somebody give any other ways or sample?

P/S: i just like master in deep about pointer

Feb 5 '06 #1
7 16365
"morz" <bl*********@gmail.com> wrote in message
news:11**********************@g47g2000cwa.googlegr oups.com
i just search for a while in c++ groups but cannot find good answer.

i have code like this:

int **ptr;
This next line should have int, not char
ptr = new char *[2];

ptr[0] = new int(5);
ptr[1] = new int(16);

i know we can delete ptr like this:

for (int i = 0; i <2; i++)
delete ptr[i];
delete ptr;

But can i delete like this? :

delete ptr;
for (int i = 0; i <2; i++)
delete ptr[i];


No, because after the

delete ptr;

ptr essentially reverts to an "uninitialized" status, so ptr[i] involves
undefined behaviour. As with all undefined behaviour, you might get away
with it, but it is foolish to try.

--
John Carson

Feb 5 '06 #2
morz wrote:
i just search for a while in c++ groups but cannot find good answer.

i have code like this:

int **ptr;
ptr = new char *[2];

ptr[0] = new int(5);
ptr[1] = new int(16);

i know we can delete ptr like this:

for (int i = 0; i <2; i++)
delete ptr[i];
delete ptr;
Correct.

But can i delete like this? :

delete ptr;
for (int i = 0; i <2; i++)
delete ptr[i];
No, you cannot: Within the for loop you are dereferencing the previously
deleted pointer ptr. The expression ptr[i] does that! Dereferencing a
deleted pointer is undefined behavior. This kind of undefined behavior can
be quite nasty a bug since very often it manifests itself in expected
behavior most of the time and explodes into your face only occasionally.
or

can somebody give any other ways or sample?

P/S: i just like master in deep about pointer


The deep mastery of pointers is knowing all the tools that allow you *not*
to use pointers in the first place. Pointers involve all sorts of nasty
pitfalls: double deletion, dereferencing after deletion, missing deletion
(aka memory leak) to name just those inherently steming from pointer use.
The problem here is that pointer management involves life time management
and is intrinsically a problem that tends to spread out over your code. The
general advice here would be to have well defined ownership (each pointer
is owned by a single object and allocation as well as deletion is the
responsibility of that object). The best idiom for that would be to confine
allocation of pointers to constructors and to put the corresponding
deallocation within the destructor.

Then there is the whole area of traps that come from the interaction of
dynamic memory allocation and stack unwinding triggered by exceptions. Let
me just give you the simplest example:

{
SomeType* some_pointer = new SomeType( some arguments );
// some code
...
delete some_pointer;
}

What happens if the code between the allocation and the delete throws an
exception and the program starts stack unwinding? The delete statement will
never be reached. However, the destructor for some_pointer will be called
and the variable will be gone: you can never make up for the missing
delete. BTW: if you look close enough you will find that the second
allocation in your program may serve as the "some code" section from this
example. In other words, your sample snippet exhibits a possible memory
leak if the second allocation fails.

Avoid pointers whenever possible. There are lots of tools that allow you to
get away without touching raw pointers most of the time: shared_ptr<T>,
auto_ptr<T>, and of course all the standard containers like std::map and
std::vector from the standard library.
Best

Kai-Uwe Bux
Feb 5 '06 #3
On Sun, 05 Feb 2006 06:51:51 -0800, morz wrote:
i have code like this:

int **ptr;
ptr = new char *[2];

ptr[0] = new int(5);
ptr[1] = new int(16);

i know we can delete ptr like this:

for (int i = 0; i <2; i++)
delete ptr[i];
dele use ote ptr;
delete [] ptr;
But can i delete like this? :

delete ptr;
for (int i = 0; i <2; i++)
delete ptr[i];
No. After "delete ptr" (or, better, "delete [] ptr") ptr is invalid and
you can't use it.
can somebody give any other ways or sample?


You can make an array of "smart pointers". Then, "delete [] ptr" will
call the destructor of each element and the smart pointer will delete the
thing it points to.

--
Ben.

Feb 5 '06 #4
In article <11**********************@g47g2000cwa.googlegroups .com>,
"morz" <bl*********@gmail.com> wrote:
i just search for a while in c++ groups but cannot find good answer.

i have code like this:

int **ptr;
ptr = new char *[2];
int or char?
ptr[0] = new int(5);
ptr[1] = new int(16);

i know we can delete ptr like this:

for (int i = 0; i <2; i++)
delete ptr[i];
delete ptr;

But can i delete like this? :

delete ptr;
for (int i = 0; i <2; i++)
delete ptr[i];

or

can somebody give any other ways or sample?


vector<shared_ptr<int> > ptr;
ptr.push_back( new int(5) );
ptr.push_back( new int(16) );

// no deleting necessary
--
Magic depends on tradition and belief. It does not welcome observation,
nor does it profit by experiment. On the other hand, science is based
on experience; it is open to correction by observation and experiment.
Feb 5 '06 #5
i know we can delete ptr like this:

for (int i = 0; i <2; i++)
delete ptr[i];
delete ptr; can somebody give any other ways or sample?

This code-fragment does not compile with my compiler.
vector<shared_ptr<int> > ptr;
ptr.push_back( new int(5) );
ptr.push_back( new int(16) );

// no deleting necessary


The error is something like

g++ smart_ptrexapl.cpp -o smart_ptrexapl
smart_ptrexapl.cpp: In function ‘int main()’:
smart_ptrexapl.cpp:10: error: no matching function for call to
‘std::vector<std::tr1::shared_ptr<int>,
std::allocator<std::tr1::shared_ptr<int> > >::push_back(int*)’
/usr/include/c++/4.0.2/bits/stl_vector.h:602: note: candidates are:
void std::vector<_Tp, _Alloc>::push_back(const _Tp&) [with _Tp =
std::tr1::shared_ptr<int>, _Alloc =
std::allocator<std::tr1::shared_ptr<int> >]

The following program is a correction of Daniel T.s fragment.

[

#include <tr1/memory>
#include <vector>

using std::tr1::shared_ptr;
using std::vector;

int main() {
vector<shared_ptr<int> > ptr;
ptr.push_back(shared_ptr<int>(new int(42)));
return 0;
}

]

Feb 6 '06 #6
int **ptr;
ptr = new char *[2];

acatually the char is int.sorry for the typo.

Wow! everybody gave good answers.

i'm interested with Daniel T. code:

vector<shared_ptr<int> > ptr;
ptr.push_back( new int(5) );
ptr.push_back( new int(16) );

// no deleting necessary

and Marco Wahl code :

#include <tr1/memory>
#include <vector>

using std::tr1::shared_ptr;
using std::vector;

int main() {
vector<shared_ptr<int> > ptr;
ptr.push_back(shared_ptr<int>(new int(42)));
return 0;

}

i would like to know any other way create pointers without delete it
after use? any other stl approach like above code? thank you

Feb 6 '06 #7
> i would like to know any other way create pointers without delete it
after use? [...]


Maybe you would like to study the auto_ptr-class that is already part
of the c++-standard and further the remaining pointer-classes besides
the shared_ptr-class from the boost library. You could start at
http://www.boost.org/libs/smart_ptr/smart_ptr.htm

Feb 6 '06 #8

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

Similar topics

3
by: Songling | last post by:
Hi gurus, Just learnt from my co-worker that it's safe to delete a null pointer. I tried it on sun box (and linux), nothing bad happens. So it seems to be true. But does it apply to all...
10
by: Piotr | last post by:
I have a class 'Statistics' which has a private attribute ' vector<int>* _x;' And in the destructor of the Statistics, I have this code to free the memory: Statistics::~Statistics() { if...
11
by: asimorio | last post by:
Hi all, If I don't new up a pointer, can I delete it? see code below: void A::foo() { char* buffer; delete buffer; return; }
4
by: asimorio | last post by:
All, Well, now i modify a bit my code: Will it make sense? void A::Foo(void* a) { char* buffer = (char*) a; delete buffer; return; }
5
by: mkaushik | last post by:
Hi everyone, Im just starting out with C++, and am curious to know how "delete <pointer>", knows about the number of memory locations to free. I read somewhere that delete frees up space...
18
by: aj | last post by:
I have the following snippet of code. On some platforms, the delete calls works, on Linux, it core dumps (memory dump) at the delete call. Am I responsible for deleting the memory that...
4
by: Rob | last post by:
If I have a function that has a variable declared inside it (which is a pointer) that can be set equal to a pointer returned from another function, do i need to delete it before returning from the...
0
by: stefan129 | last post by:
Hey forum members, I'm exploring options for SSL certificates for multiple domains. Has anyone had experience with multi-domain SSL certificates? Any recommendations on reliable providers or specific...
0
Git
by: egorbl4 | last post by:
Скачал я git, хотел начать настройку, а там вылезло вот это Что это? Что мне с этим делать? ...
0
by: MeoLessi9 | last post by:
I have VirtualBox installed on Windows 11 and now I would like to install Kali on a virtual machine. However, on the official website, I see two options: "Installer images" and "Virtual machines"....
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, youll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: Aftab Ahmad | last post by:
Hello Experts! I have written a code in MS Access for a cmd called "WhatsApp Message" to open WhatsApp using that very code but the problem is that it gives a popup message everytime I clicked on...
0
by: Aftab Ahmad | last post by:
So, I have written a code for a cmd called "Send WhatsApp Message" to open and send WhatsApp messaage. The code is given below. Dim IE As Object Set IE =...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
by: marcoviolo | last post by:
Dear all, I would like to implement on my worksheet an vlookup dynamic , that consider a change of pivot excel via win32com, from an external excel (without open it) and save the new file into a...

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.