473,734 Members | 2,286 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 2280
* 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
1260
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 would have changed so that it is not working for me suddenly.
4
3432
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
1454
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
4222
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
4998
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 add a Close function to the classes, but is the C++ way to just put
4
1689
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: function delacc(){ $retrievedusr = $_COOKIE; $dsql1 = "DELETE FROM mpw_3_5_test_dbase_users...
0
8946
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
8778
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9453
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...
1
9242
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
6739
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 instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4551
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 the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4814
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2730
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2180
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.