473,569 Members | 2,813 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

delete pointers: why is this working!!??

i believe deleting an already delete pointer should give me a
segmentation fault! Why, then, is the following working? I am using gcc
version 3.0.2.

#include<stdio. h>
#include <string>
using namespace std;

int main()
{
string * j = new string("this prog should dump core!");
printf("\n%s\n" ,j->c_str());
delete j;
delete j;
}

Jul 23 '05 #1
11 2264
* mufasa:
i believe deleting an already delete pointer should give me a
segmentation fault! Why, then, is the following working? I am using gcc
version 3.0.2.

#include<stdio. h>
#include <string>
using namespace std;

int main()
{
string * j = new string("this prog should dump core!");
printf("\n%s\n" ,j->c_str());
delete j;
delete j;
}


It's Undefined Behavior, which means that any result whatsoever is
acceptable as far as the standard is concerned.

General advice as you're learning the language:

1) Don't use raw pointers.
2) Don't use raw pointers.
3) Don't ... You get the idea.

Also, consider using C++ iostreams, which are more type-safe than C printf.

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Jul 23 '05 #2
mufasa wrote:
i believe deleting an already delete pointer should give me a
segmentation fault!
No, it should give you undefined behavior.
Why, then, is the following working?
Because that is one instance of "undefined behavior".
I am using gcc version 3.0.2.

#include<stdio. h>
#include <string>
using namespace std;

int main()
{
string * j = new string("this prog should dump core!");
printf("\n%s\n" ,j->c_str());
delete j;
delete j;
}


Jul 23 '05 #3
the std::string class might've used a reference counting allocation for the
actually string content. The reference counting rule can be "delete the
content if reference count drops to zero; if the reference count is
negative, don't do any deletion".

you should refer to the actually implementation to see what is going on
there.

don't do double deletion, that's all.

"mufasa" <so*****@gmail. com> wrote in message
news:11******** **************@ l41g2000cwc.goo glegroups.com.. .
i believe deleting an already delete pointer should give me a
segmentation fault! Why, then, is the following working? I am using gcc
version 3.0.2.

#include<stdio. h>
#include <string>
using namespace std;

int main()
{
string * j = new string("this prog should dump core!");
printf("\n%s\n" ,j->c_str());
delete j;
delete j;
}

Jul 23 '05 #4
[top posting fixed]

Kehuei Huang wrote:

"mufasa" <so*****@gmail. com> wrote in message
news:11******** **************@ l41g2000cwc.goo glegroups.com.. .
i believe deleting an already delete pointer should give me a
segmentatio n fault! Why, then, is the following working? I am using gcc
version 3.0.2.

#include<stdi o.h>
#include <string>
using namespace std;

int main()
{
string * j = new string("this prog should dump core!");
printf("\n%s\n" ,j->c_str());
delete j;
delete j;
}

the std::string class might've used a reference counting allocation

for the actually string content. The reference counting rule can be "delete the
content if reference count drops to zero; if the reference count is
negative, don't do any deletion".
I don't see how your /proposed/ reference counting avoid undefined
behavior, when you are deleting the pointer j twice.

you should refer to the actually implementation to see what is going on
there.

don't do double deletion, that's all.


Krishanu
Jul 23 '05 #5

Krishanu Debnath wrote:
[top posting fixed]

Kehuei Huang wrote:

"mufasa" <so*****@gmail. com> wrote in message
news:11******** **************@ l41g2000cwc.goo glegroups.com.. .
i believe deleting an already delete pointer should give me a
segmentatio n fault! Why, then, is the following working? I am using gccversion 3.0.2.

#include<stdi o.h>
#include <string>
using namespace std;

int main()
{
string * j = new string("this prog should dump core!");
printf("\n%s\n" ,j->c_str());
delete j;
delete j;
}

> the std::string class might've used a reference counting allocation for the
> actually string content. The reference counting rule can be

"delete the > content if reference count drops to zero; if the reference count is > negative, don't do any deletion".


I don't see how your /proposed/ reference counting avoid undefined
behavior, when you are deleting the pointer j twice.
>
> you should refer to the actually implementation to see what is going on > there.
>
> don't do double deletion, that's all.


Krishanu


Jul 23 '05 #6
Hi

Sorry about the previous "empty" message.

I'm using glibc-2.3.4 with gcc-3.3.5.
When I do delete twice my program aborts:
"*** glibc detected *** double free or corruption (fasttop): 0x08049db0
***
Aborted"

I didn't expect such a descriptive error message.

Anyway, new and delete are merely mechanisms of telling the system,
which sections of memory you're using.
After calling the delete operator on a pointer, the memory pointed to
becomes available to the system again. Until the system reasigns that
memory you'll be able to "access" it.
ie:
int& a = new int;
a = 5;
cout << a; // "5"
delete &a;
cout << a; // "5"
.... // some time later
cout << a; // whatever's in memory at that time.
It is posible that having the two delete statements next to each other,
would allow your program to run without any problems.

Remember new and delete are class (static) operators not instance
operators.
It is posible to call them with out having any valid instances.

Also if you have to use raw pointer, set them to null after calling the
delete, then you'll be able to tell if it's safe to use.
IE:
SomeClass* sc = new SomeClass();
.... // some time later
if (sc) // true
{
sc->someFunction() ;
}
.... // some time later
if (sc) // true
{
delete sc;
sc = 0;
}
.... // some time later
if (sc) // false
{
sc->someFunction() ;
}

Joe

Jul 23 '05 #7
How about this code? Is the delete statement here trying to break some
ownership rules (I think that's the case .. still verifying)?
Because this segment is dumping core as well!

#include<stdio. h>
#include <string>
using namespace std;

int main()
{
string someString("abc ");
char * c= new char[someString.leng th()];

c = const_cast<char *>(someString.c _str());

printf("\n%s\n" ,c);
delete [] c;
}

Jul 23 '05 #8
jo*****@dariel. co.za wrote:
Hi

Sorry about the previous "empty" message.
Post with proper context/quote is much appreciated.

I'm using glibc-2.3.4 with gcc-3.3.5.
[all compiler/implementation specific details snipped]
After calling the delete operator on a pointer, the memory pointed to
becomes available to the system again. Until the system reasigns that
memory you'll be able to "access" it.
ie:
int& a = new int;
[invalid c++ code fragments snipped]


It is posible that having the two delete statements next to each other,
would allow your program to run without any problems.


After invoking UB, it can run without any problems, it may also order
a 'peppy paneer pizza' from Pizza Hut for you. Best of luck !

Krishanu
Jul 23 '05 #9
mufasa wrote:
How about this code? Is the delete statement here trying to break some
ownership rules (I think that's the case .. still verifying)?
Because this segment is dumping core as well!

#include<stdio. h>
#include <string>
using namespace std;

int main()
{
string someString("abc ");
char * c= new char[someString.leng th()];
Here, you allocate an array of 3 char and assign its starting address to c.
c = const_cast<char *>(someString.c _str());
Here, you overwrite c, losing the only pointer you had to your dynamically
allocated array. This is a memory leak. Also, the const_cast is a *very*
bad idea, as are almost all const_casts.
printf("\n%s\n" ,c);
delete [] c;
Here, you try to delete the array that was returned by c_str(), so the
answer to your question is yes, you break an ownership rule. You don't even
know whether the pointer returned by c_str() actually points to dynamically
allocated memory.
}


Jul 23 '05 #10

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

Similar topics

5
2845
by: Andrew DeFaria | last post by:
I created the following .sql file to demonstrate a problem I'm having. According to the manual: If |ON DELETE CASCADE| is specified, and a row in the parent table is deleted, then InnoDB automatically deletes also all those rows in the child table whose foreign key values are equal to the referenced key value in the parent row. However:
1
1254
by: Sunshine | last post by:
Pretty new to javascript so please help. Why isn't this working in my validateform()? if (document.This.strOld.value.compareTo(Session("strPassword")) != 0) { alert("Current password incorrect"); return false; } If I write out Session("strPassword") the value is 'password'. What am I doing wrong?
0
292
by: Nedu N | last post by:
Hi Experts, All of sudden the delete confirmation is not working for me on my datagrid (it was working 2 days ago..couldn't figure out the cause). I am trying to add an 'onsubmit' attribute to the Delete link button (in the onItemCreated event...and i tried with onItemDataBound event too).. Is there something (some options/setting) i...
4
3428
by: Pipo | last post by:
The problem: I create a very simple custom control: public class cLabel : System.Web.UI.WebControls.Label { } I place the cLabel in a user control. When I place the user control on a page I get this exception:
9
1444
by: pavan734 | last post by:
Hello, I have a array of double pointers as shown below dummy_class **ptr ; //assume dummy class to be some c++ class I have allocated it like this: for(int i = 0 ; i<10 ; i++) { ptr = new dummy_class* ; for(int j=0 ; j<5 ; j++) // This 5 is because of previous allocation of 5
7
4218
by: Anil Gupte | last post by:
Private Sub mnu2Exit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnu2Exit.Click Dim fDir As String = Path.GetDirectoryName(L3Global.VideoFileName) File.Delete(L3Global.VideoFileName) ' The following is not working - reports directory not empty exception ' Directory.Delete(fDir)
8
4978
by: TBass | last post by:
Hi, Switching some code from C to C++, and I have a destructor question: In the C code, when the program wants to close and free all memory, I have them call a Close function. The linked-lists get free'd. In the C++ versions, my class has a linked list items of another class, which also has a linked list of another class. I was going to...
4
1680
by: wangers16 | last post by:
I have the following code in my website and it is supposed to delete a user account along with all associated records, however it doesn't delete any of the records, the function is working, beacuse I also have a logout function that gets called afterwards that is working, it just seems to be skipping the delete commands. Here is my code: ...
0
7703
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...
0
8138
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...
0
7983
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...
0
6287
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...
1
5514
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...
0
3657
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...
0
3647
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1228
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
946
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...

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.