473,408 Members | 2,832 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,408 software developers and data experts.

delete the dynamically allocated memory twice causes error

tom
why delete the dynamically allocated memory twice causes an error, see
the code below:

int _tmain(int argc, _TCHAR* argv[])
{
int *pi = new int(12);
cout<<*pi;
delete pi;
delete pi;
}

Jul 24 '07 #1
15 1760
tom wrote:
why delete the dynamically allocated memory twice causes an error, see
the code below:

int _tmain(int argc, _TCHAR* argv[])
{
int *pi = new int(12);
cout<<*pi;
delete pi;
delete pi;
}
Because after the first 'delete' the pointer does not point to any
valid dynamically allocated object any more. Passing an invalid (or
dangling) pointer to 'delete' has undefined behaviour. In your case
it manifests itself as an error. In some cases it can go unnoticed.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Jul 24 '07 #2
tom wrote:
why delete the dynamically allocated memory twice causes an error, see
the code below:
From the ISO C++ Standard:

If the argument given to a deallocation function in the standard
library is a pointer that is not the null pointer value (4.10), the
deallocation function shall deallocate the storage referenced by the
pointer, rendering invalid all pointers referring to any part of the
deallocated storage. The effect of using an invalid pointer value
(including passing it to a deallocation function) is undefined.33)

33) On some implementations, it causes a system-generated runtime fault.

Why do you want to do that?


Brian

Jul 24 '07 #3
Alf P. Steinbach wrote:
* tom:
>why delete the dynamically allocated memory twice causes an error,
see the code below:

int _tmain(int argc, _TCHAR* argv[])
{
int *pi = new int(12);
cout<<*pi;
delete pi;
delete pi;
}

There's no such thing as _tmain in standard C++. There's no such
thing as _TCHAR in standard C++. Your code does not compile. This
group is for discussing standard C++. Please fix your example, and
repost.
Chill, Alf. For all we know, _tmain is a function OP wrote himself.
And what _TCHAR is *is* quite irrelevant to the question asked. Of
course "_TCHAR" is a reserved identifier which makes it prohibited
in the program outside of the library implementation. And 'cout' is
not really defined here. But, hey, so what? To ask a question like
that the code doesn't even have to be complete. It should be enough
to write

int *pi = new int(12);
// use pi somehow
delete pi;
delete pi;

to get a normal answer to the question. Perhaps you should get off
your high moderator's horse once in a while, eh?

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Jul 24 '07 #4
tom
On Jul 25, 6:43 am, "Victor Bazarov" <v.Abaza...@comAcast.netwrote:
Alf P. Steinbach wrote:
* tom:
why delete the dynamically allocated memory twice causes an error,
see the code below:
int _tmain(int argc, _TCHAR* argv[])
{
int *pi = new int(12);
cout<<*pi;
delete pi;
delete pi;
}
There's no such thing as _tmain in standard C++. There's no such
thing as _TCHAR in standard C++. Your code does not compile. This
group is for discussing standard C++. Please fix your example, and
repost.

Chill, Alf. For all we know, _tmain is a function OP wrote himself.
And what _TCHAR is *is* quite irrelevant to the question asked. Of
course "_TCHAR" is a reserved identifier which makes it prohibited
in the program outside of the library implementation. And 'cout' is
not really defined here. But, hey, so what? To ask a question like
that the code doesn't even have to be complete. It should be enough
to write

int *pi = new int(12);
// use pi somehow
delete pi;
delete pi;

to get a normal answer to the question. Perhaps you should get off
your high moderator's horse once in a while, eh?

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask- Hide quoted text -

- Show quoted text -
I'm new here. And that's why I need to make a post here and ask
questions.
And my question is not relevant to the name of the function and type
of the variable. And
as far as I know the language could have a standard, but there won't
be a compiler 100% follow the standard.
Correct me if I'm wrong.

Jul 25 '07 #5
"tom" <px****@gmail.comwrote in message
news:11*********************@g12g2000prg.googlegro ups.com...
On Jul 25, 6:43 am, "Victor Bazarov" <v.Abaza...@comAcast.netwrote:
>Alf P. Steinbach wrote:
* tom:
why delete the dynamically allocated memory twice causes an error,
see the code below:
>int _tmain(int argc, _TCHAR* argv[])
{
int *pi = new int(12);
cout<<*pi;
delete pi;
delete pi;
}
There's no such thing as _tmain in standard C++. There's no such
thing as _TCHAR in standard C++. Your code does not compile. This
group is for discussing standard C++. Please fix your example, and
repost.

Chill, Alf. For all we know, _tmain is a function OP wrote himself.
And what _TCHAR is *is* quite irrelevant to the question asked. Of
course "_TCHAR" is a reserved identifier which makes it prohibited
in the program outside of the library implementation. And 'cout' is
not really defined here. But, hey, so what? To ask a question like
that the code doesn't even have to be complete. It should be enough
to write

int *pi = new int(12);
// use pi somehow
delete pi;
delete pi;

to get a normal answer to the question. Perhaps you should get off
your high moderator's horse once in a while, eh?

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask- Hide quoted
text -

- Show quoted text -

I'm new here. And that's why I need to make a post here and ask
questions.
And my question is not relevant to the name of the function and type
of the variable. And
as far as I know the language could have a standard, but there won't
be a compiler 100% follow the standard.
Correct me if I'm wrong.
I wouldn't worry about it too much Tom. Some users get upset at a few things
and refuse to answer questions if a post contains them. Such as:
void main()
main MUST return an int.

int _tmain(int argc, _TCHAR* argv[])
this is how windows specific code handles the mainline in code. Even though
everyone knows there IS a main() somewhere that calls _tmain() some people
get upset because it's not called main.

C/C++
The langauge is not called C/C++ it's called C or C++, pick one

Basically, when someone responds with replies like this without answering
the question, I ignore them. Although you should get into the habit of
renaming _tmain to main when you post, etc... just so you don't have to
listen to people like this bitch.
Jul 25 '07 #6
"Alf P. Steinbach" <al***@start.nowrote in message
news:13*************@corp.supernews.com...
>* Jim Langston:
>"tom" <px****@gmail.comwrote in message
>>I'm new here. And that's why I need to make a post here and ask
questions.
And my question is not relevant to the name of the function and type
of the variable. And
as far as I know the language could have a standard, but there won't
be a compiler 100% follow the standard.
Correct me if I'm wrong.

I wouldn't worry about it too much Tom. Some users get upset at a few
things and refuse to answer questions if a post contains them. Such as:
void main()
main MUST return an int.

int _tmain(int argc, _TCHAR* argv[])
this is how windows specific code handles the mainline in code. Even
though everyone knows there IS a main() somewhere that calls _tmain()
some people get upset because it's not called main.

C/C++
The langauge is not called C/C++ it's called C or C++, pick one

Basically, when someone responds with replies like this without answering
the question, I ignore them. Although you should get into the habit of
renaming _tmain to main when you post, etc... just so you don't have to
listen to people like this bitch.

If we start accepting _tmain without comment, then in a few moments we'll
be back to 1995 situation where clc++ had devolved into a Windows
programming group. There are enough Windows programming groups. There
are only two high quality C++ groups, and let's endeavour to keep them.
I agree, we should comment on _tmain(). But commenting without answering the
OP's question just gets your post ignored.

I find it better if I want to comment to comment on it, then answer the
question.
Jul 25 '07 #7
tom
On Jul 25, 8:26 am, "Jim Langston" <tazmas...@rocketmail.comwrote:
"Alf P. Steinbach" <al...@start.nowrote in messagenews:13*************@corp.supernews.com...


* Jim Langston:
"tom" <pxk...@gmail.comwrote in message
I'm new here. And that's why I need to make a post here and ask
questions.
And my question is not relevant to the name of the function and type
of the variable. And
as far as I know the language could have a standard, but there won't
be a compiler 100% follow the standard.
Correct me if I'm wrong.
I wouldn't worry about it too much Tom. Some users get upset at a few
things and refuse to answer questions if a post contains them. Such as:
void main()
main MUST return an int.
int _tmain(int argc, _TCHAR* argv[])
this is how windows specific code handles the mainline in code. Even
though everyone knows there IS a main() somewhere that calls _tmain()
some people get upset because it's not called main.
C/C++
The langauge is not called C/C++ it's called C or C++, pick one
Basically, when someone responds with replies like this without answering
the question, I ignore them. Although you should get into the habit of
renaming _tmain to main when you post, etc... just so you don't have to
listen to people like this bitch.
If we start accepting _tmain without comment, then in a few moments we'll
be back to 1995 situation where clc++ had devolved into a Windows
programming group. There are enough Windows programming groups. There
are only two high quality C++ groups, and let's endeavour to keep them.

I agree, we should comment on _tmain(). But commenting without answering the
OP's question just gets your post ignored.

I find it better if I want to comment to comment on it, then answer the
question.- Hide quoted text -

- Show quoted text -
OK, thanks a lot. I think I do learn something from this discussion.
And I will use "int main" later and get rid of windows specific. And
also I think I quite agree your philosophy on this language.

Jul 25 '07 #8
tom wrote:
why delete the dynamically allocated memory twice causes an error, see
the code below:

int _tmain(int argc, _TCHAR* argv[])
{
int *pi = new int(12);
cout<<*pi;
delete pi;
delete pi;
}
Well, there exists a C++ implementation which *is able to* check whether a
pointer is valid and safe to delete, but that will lose some efficiency. For
the same reason, C++ won't set the pointer to `NULL' after delete. Another
example is that C++ also won't check whether an array index is out of bound.

You know, C++ won't do anything which make programmer easier but lose
efficiency. C++ give both the dominative rights and risk to you.
Jul 25 '07 #9
Jim Langston wrote:
>
I wouldn't worry about it too much Tom. Some users get upset at a few things
and refuse to answer questions if a post contains them. Such as:
void main()
main MUST return an int.

int _tmain(int argc, _TCHAR* argv[])
this is how windows specific code handles the mainline in code. Even though
everyone knows there IS a main() somewhere that calls _tmain() some people
get upset because it's not called main.

C/C++
The langauge is not called C/C++ it's called C or C++, pick one

Basically, when someone responds with replies like this without answering
the question, I ignore them. Although you should get into the habit of
renaming _tmain to main when you post, etc... just so you don't have to
listen to people like this bitch.

Hello Jim,

That was a very sensible post there. Thanks for the mature words. You
are correct, constructive comments are alway helpful. I agree that
corrections are needed to non-standard code, but these corrections
should be accompanied with helpful comments that try to solve the
problem. People learn from these kinds of posts. Most important, it
helps them to learn the distinction between standard and nonstandard code.

regards,
->HS
Jul 25 '07 #10
On Jul 25, 2:20 am, "Alf P. Steinbach" <al...@start.nowrote:
* Jim Langston:
"tom" <pxk...@gmail.comwrote in message
I'm new here. And that's why I need to make a post here and
ask questions. And my question is not relevant to the name
of the function and type of the variable. And as far as I
know the language could have a standard, but there won't be
a compiler 100% follow the standard. Correct me if I'm
wrong.
Just to answer his question: most compilers don't follow the
standard 100%, or even try to. Comeau does, but I don't know of
another. Also, you typically need special options to get as
close as possible to the standard. By default, most compilers
can be very, very far from the standard.

On the other hand, the subject of this group is more or less
portable C++. The way different compilers deviate from the
standard isn't usually very portable. (The one big exception
being that most compilers don't implement export.) So in
general, you should try to find out what is and what isn't
standard (and which standard---in my own work, I use a lot of
standards: C++, Posix, quite a few RFC's...). And avoid what
isn't standard (or rather, what isn't more or less universally
supported) when you don't need it.
I wouldn't worry about it too much Tom. Some users get upset
at a few things and refuse to answer questions if a post
contains them. Such as:
void main()
main MUST return an int.
int _tmain(int argc, _TCHAR* argv[])
this is how windows specific code handles the mainline in
code. Even though everyone knows there IS a main()
somewhere that calls _tmain() some people get upset because
it's not called main.
C/C++
The langauge is not called C/C++ it's called C or C++, pick one
Depending on the question, this may or may not be relevant. I
use "C/C++" myself when talking about things like sequence
points, or what the standard requires of an int.
Basically, when someone responds with replies like this without answering
the question, I ignore them. Although you should get into the habit of
renaming _tmain to main when you post, etc... just so you don't have to
listen to people like this bitch.
If we start accepting _tmain without comment, then in a few moments
we'll be back to 1995 situation where clc++ had devolved into a Windows
programming group.
Do you really think so? My impression is that the web has moved
on, and that the sort of people who don't care, and who created
the 1995 situation have 1) moved on to newer, more in languages,
and 2) aren't even aware that newsgroups exist---they're more
into blogs and such today. This is obviously speculation on my
part, but one thing is clear: around 1995, this group did become
unusable, because of off topic postings, and that constantly
signaling such postings didn't change anything. And that today,
there's no real problem. The poster in this thread had a real
C++ question, which obviously doesn't depend on the platform,
and his posting would have been accepted even in a moderated
group. As Jim said, a short comment reminding him (or informing
him to begin with) that _tmain wasn't standard C++ wouldn't
necessarily be a bad idea, as a secondary comment in a posting
answering his real question, but it hardly justifies a complete
posting in itself. The situation concerning off topic postings
here is far from being bad enough to require a knee-jerk
reaction, and from history, I can assure you that a knee-jerk
reaction won't change anything anyway.

--
James Kanze (GABI Software) email:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

Jul 25 '07 #11
On Jul 25, 3:10 am, Junhui Tong <tongjun...@live.comwrote:
tom wrote:
why delete the dynamically allocated memory twice causes an error, see
the code below:
int _tmain(int argc, _TCHAR* argv[])
{
int *pi = new int(12);
cout<<*pi;
delete pi;
delete pi;
}
Well, there exists a C++ implementation which *is able to*
check whether a pointer is valid and safe to delete, but that
will lose some efficiency. For the same reason, C++ won't set
the pointer to `NULL' after delete.
The main reason here has nothing to do with efficiency. It has
to do with the fact that it doesn't buy you anything, and even
more so with the fact that the "pointer" isn't necessarily an
lvalue which can be modified. (I'd say that over half my
deletes are "delete this".)
Another example is that C++ also won't check whether an array
index is out of bound.
C++ leaves that up to the implementation. A good implementation
will check, at least in the case where it knows the bounds.
You know, C++ won't do anything which make programmer easier
but lose efficiency.
C++ (like C) leaves much behavior undefined intentionally just
so that an implementation can check (but isn't required to).
Good implementations do check, when it is reasonable to do so.

--
James Kanze (GABI Software) email:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Jul 25 '07 #12
tom wrote:
why delete the dynamically allocated memory twice causes an error, see
the code below:

int _tmain(int argc, _TCHAR* argv[])
{
int *pi = new int(12);
cout<<*pi;
delete pi;
delete pi;
}

This might help (see point 16.8):

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

regards,
->HS
Jul 25 '07 #13

Junhui Tong <to********@live.comwrote in message...
tom wrote:
int _tmain(int argc, _TCHAR* argv[]){
int *pi = new int(12);
cout<<*pi;
delete pi;
delete pi;
}
[snip]
>
You know, C++ won't do anything which **make programmer easier**
but lose efficiency.
Not if you use 'C' code (replace 'new' with 'malloc' in OPs code above,
etc.).
In 'C++', I'd just do:

#include <iostream>
#include <vector>
int main(){
std::vector<intpi( 1, 12 );
// Tong "Another example is that C++ also won't check whether
// an array index is out of bound."
// And what does '.at()' do?
std::cout << pi.at(0);
return 0;
}

Much 'easier'! How much 'efficiency' did that give up?
Now add some more:

int *pi = new int(12);
int *pi2 = new int(12);
// ....
int *pi299 = new int(12);
int *pi300 = new int(12);
// yeah, array is better, but you still need to 'delete[]'
vs.
std::vector<intpi( 300, 12 );

Now where's your 'efficiency'?
Which would you choose?
'C++' was designed to be [1] a faster way to program ('C'). That's the
'efficiency'!

[1] among other considerations (type safety?). <G>
--
Bob R
POVrookie
Jul 25 '07 #14
BobR wrote:
[snip]
#include <iostream>
#include <vector>
int main(){
std::vector<intpi( 1, 12 );
// Tong "Another example is that C++ also won't check whether
// an array index is out of bound."
// And what does '.at()' do?
but vector is not the built-in `array'.
std::cout << pi.at(0);
return 0;
}

Much 'easier'! How much 'efficiency' did that give up?
Yes, `at' lose efficiency, here is a typical implementation of vector<>::at:
const_reference at(size_type _Pos) const
{
if (size() <= _Pos) // waste an extra compare here
_Xran();
return (*(begin() + _Pos));
}
Now add some more:

int *pi = new int(12);
int *pi2 = new int(12);
// ....
int *pi299 = new int(12);
int *pi300 = new int(12);
// yeah, array is better, but you still need to 'delete[]'
vs.
std::vector<intpi( 300, 12 );

Now where's your 'efficiency'?
Which would you choose?
When I talk "C++", I only mean the syntax, not including the extra libraries
such as STL, though it's a part of C++.
sorry for my poor english, but When I talk "efficiency", I only mean the
runtime efficiency.

'C++' was designed to be [1] a faster way to program ('C'). That's the
a faster way to program without losing efficiency
'efficiency'!
May be we consider `efficiency' in different aspects.
[1] among other considerations (type safety?). <G>
--
Bob R
POVrookie

Jul 26 '07 #15
Junhui Tong wrote:
:: BobR wrote:
:: [snip]
::: #include <iostream>
::: #include <vector>
::: int main(){
::: std::vector<intpi( 1, 12 );
::: // Tong "Another example is that C++ also won't check whether
::: // an array index is out of bound."
::: // And what does '.at()' do?
:: but vector is not the built-in `array'.
::: std::cout << pi.at(0);
::: return 0;
::: }
:::
::: Much 'easier'! How much 'efficiency' did that give up?
:: Yes, `at' lose efficiency, here is a typical implementation of
:: vector<>::at: const_reference at(size_type _Pos) const
:: {
:: if (size() <= _Pos) // waste an extra compare here
:: _Xran();
:: return (*(begin() + _Pos));
:: }
::

We might be losing very little efficiency for an added check. The
compiler I use, will recognize that in the code

for (std::size_t i = 0; i < v.size(), ++i)
cout << v.at(i);

the two tests "i < v.size()" and "size() <= _Pos" both compare the
loop-variable against size(). So it will merge the code into the loop
termination test, resulting in "size() <= _Pos" in effect being
evaluated only once, before the loop!

An extremely small price performance-wise!
Bo Persson
Jul 26 '07 #16

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

Similar topics

6
by: Alexander Stippler | last post by:
Hi, I have some question about the usage of delete. I have some reference counted classes, all derived from SharedObject. It's destructor looks like this: ~SharedObject() { if...
14
by: A | last post by:
Hi, Consider this: char* ptr = "a string"; Is ptr a pointer to a dynamically created object for which i must use the delete operator to deallocate memory? I'm sure the "a string" part...
16
by: cppaddict | last post by:
Hi, I am deleting some objects created by new in my class destructor, and it is causing my application to error at runtime. The code below compiles ok, and also runs fine if I remove the body...
3
by: William Payne | last post by:
Hi, I have a class that allocates some memory dynamically in its (only) constructor. In my destructor I have a call to delete which corresponds to the new in the constructor. So far so good....
9
by: Venn Syii | last post by:
I have the following line of code: if (MyData) { delete MyData; MyData= NULL; } Below is MyData: SomeDataStructure *MyData;
5
by: lixiaoyao | last post by:
hi all I use matrix & vector function to allocate the space myself in c, typedef struct matrix_array newdata; struct matrix_array{ float **sy,*sxx; }; newdata ndata;//new data struct...
13
by: Franklin Li | last post by:
Hi All, I find one example codes as below: int send() { char msg; ... delete msg; ..
7
by: Yi | last post by:
Two questions about the following code sample: --- code begins --- //class IPv4 is defined elsewhere list<IPv4ip_list; for (int i=1; i<=9; i++) { char addr; sprintf(addr, "%d.%d.%d.%d",...
2
by: presencia | last post by:
Hi everyone, I have written a small program running fine until a Segmentation fault. Using a debugger I have localized the function the fault happens in. The Signal appears during a call to delete...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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...
0
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...
0
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...
0
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...

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.