473,322 Members | 1,562 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.

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 16384
"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: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
1
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: 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...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
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
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...

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.