I'm using an STL map in my code.
My application sometimes tries to delete things twice from the map.
This leads to a crash in my current code. The problem is probably the
way I check whether it is necessary to delete something (line 44 and 52
in below code).
In the below code the problem is demonstrated, line 65 will cause a
segmentation fault.
1 #include <iostream>
2 #include <cstdlib>
3 #include <map>
4
5 using namespace std;
6
7 class MyClass
8 {
9 public:
10 MyClass(int);
11 ~MyClass();
12 void show();
13 private:
14 int nr_;
15 };
16
17 MyClass::MyClas s(int nr) : nr_(nr)
18 {
19 cout << "MyClass: " << nr_ << " constructed" << endl;
20 }
21
22 MyClass::~MyCla ss()
23 {
24 cout << "MyClass: " << nr_ << " destructed" << endl;
25 }
26
27 void MyClass::show()
28 {
29 cout << "Show this MyClass: " << nr_ << endl;
30 }
31
32 typedef map<int, MyClass *> RtdmCyclicTimer Map;
33
34 int main(void)
35 {
36 RtdmCyclicTimer Map cyclicRtdmTimer _;
37 map<int, MyClass *>::const_itera tor cyclicRtdmIt;
38
39 // create 1 & 2
40 cyclicRtdmTimer _[1] = new MyClass(11);
41 cyclicRtdmTimer _[2] = new MyClass(22);
42
43 // delete 2
44 if (cyclicRtdmTime r_[2]) {
45 delete cyclicRtdmTimer _[2];
46 cyclicRtdmTimer _.erase(2);
47 } else {
48 cout << "delete 2 failed" << endl;
49 }
50
51 // delete 2 AGAIN
52 if (cyclicRtdmTime r_[2]) {
53 delete cyclicRtdmTimer _[2];
54 cyclicRtdmTimer _.erase(2);
55 } else {
56 cout << "delete 2[2] failed" << endl;
57 }
58
59 // show map -> NOW IT WILL CRASH
60 cout << endl << "going to show map entries" << endl;
61 for
(cyclicRtdmIt=c yclicRtdmTimer_ .begin();cyclic RtdmIt!=cyclicR tdmTimer_.end() ;
++cyclicRtdmIt) {
62 int tKey = cyclicRtdmIt->first;
63 MyClass *mcPtr = cyclicRtdmIt->second;
64 cout << "map entry found: key=" << tKey << ", valP=" <<
mcPtr << ", val=";
65 mcPtr->show();
66 }
67 }
68
This is because line 52 somehow increases the internal map size from 1
to 2 entries.
Isn't it allowed to refer to deleted entries ?
Must it be done with an iterator ? 10 2144 bo*******@wanad oo.nl wrote: I'm using an STL map in my code. My application sometimes tries to delete things twice from the map. This leads to a crash in my current code. The problem is probably the way I check whether it is necessary to delete something (line 44 and 52 in below code).
Yes.
In the below code the problem is demonstrated, line 65 will cause a segmentation fault.
1 #include <iostream> 2 #include <cstdlib> 3 #include <map> 4 5 using namespace std; 6 7 class MyClass 8 { 9 public: 10 MyClass(int); 11 ~MyClass(); 12 void show(); 13 private: 14 int nr_; 15 }; 16 17 MyClass::MyClas s(int nr) : nr_(nr) 18 { 19 cout << "MyClass: " << nr_ << " constructed" << endl; 20 } 21 22 MyClass::~MyCla ss() 23 { 24 cout << "MyClass: " << nr_ << " destructed" << endl; 25 } 26 27 void MyClass::show() 28 { 29 cout << "Show this MyClass: " << nr_ << endl; 30 } 31 32 typedef map<int, MyClass *> RtdmCyclicTimer Map; 33 34 int main(void) 35 { 36 RtdmCyclicTimer Map cyclicRtdmTimer _; 37 map<int, MyClass *>::const_itera tor cyclicRtdmIt; 38 39 // create 1 & 2 40 cyclicRtdmTimer _[1] = new MyClass(11); 41 cyclicRtdmTimer _[2] = new MyClass(22); 42 43 // delete 2 44 if (cyclicRtdmTime r_[2]) { 45 delete cyclicRtdmTimer _[2]; 46 cyclicRtdmTimer _.erase(2); 47 } else { 48 cout << "delete 2 failed" << endl; 49 } 50 51 // delete 2 AGAIN 52 if (cyclicRtdmTime r_[2]) { 53 delete cyclicRtdmTimer _[2]; 54 cyclicRtdmTimer _.erase(2); 55 } else { 56 cout << "delete 2[2] failed" << endl; 57 } 58 59 // show map -> NOW IT WILL CRASH 60 cout << endl << "going to show map entries" << endl; 61 for
(cyclicRtdmIt=c yclicRtdmTimer_ .begin();cyclic RtdmIt!=cyclicR tdmTimer_.end() ; ++cyclicRtdmIt) { 62 int tKey = cyclicRtdmIt->first; 63 MyClass *mcPtr = cyclicRtdmIt->second; 64 cout << "map entry found: key=" << tKey << ", valP=" << mcPtr << ", val="; 65 mcPtr->show(); 66 } 67 } 68
This is because line 52 somehow increases the internal map size from 1 to 2 entries.
If operator[] doesn't find the element you are searching for, it creates
that element. Otherwise, line 40 and 41 couldn't work the way they do.
Since you don't assign anything to it in line 52, the value is probably
indeterminate and cannot be used with delete.
Must it be done with an iterator ?
Yes. Use the find() member function instead of operator[]. This will never
create elements. If the element is found, you get an iterator to it,
otherwise you get end().
> 51 // delete 2 AGAIN 52 if (cyclicRtdmTime r_[2]) {
The problem is here. This implicitly adds an element to the map and
initializes the pointer with NULL. When you try to dereference that pointer
later, you get a segfault.
You could use the following check instead:
if (cyclicRtdmTime r_.find(2) != cyclicRtdmTimer _.end()) {
Best wishes,
--
Andrei Tarassov
software engineer
Altiris, Inc. www.altiris.com
Rolf Magnus wrote: If operator[] doesn't find the element you are searching for, it creates that element. Otherwise, line 40 and 41 couldn't work the way they do. Since you don't assign anything to it in line 52, the value is probably indeterminate and cannot be used with delete.
Ok, forget that. Andrei is right. The newly added pointer is initialized to
a null pointer, and since you only remove it if it's not a null pointer, it
stays in your map. Later, when you try to dereference it, your program
crashes.
On Thu, 27 Apr 2006 12:34:27 +0300, Andrei Tarassov
<at*******@alti ris.ee> wrote: 51 // delete 2 AGAIN 52 if (cyclicRtdmTime r_[2]) {
The problem is here. This implicitly adds an element to the map and initializes the pointer with NULL. When you try to dereference that pointer later, you get a segfault.
Examples like the above demonstrate that STL is designed for values
only, not for pointers. Unfortunately that fact is not conveyed in
most STL books and tutorials.
Best wishes,
Roland Pibinger bo*******@wanad oo.nl wrote: I'm using an STL map in my code. My application sometimes tries to delete things twice from the map. This leads to a crash in my current code. The problem is probably the way I check whether it is necessary to delete something (line 44 and 52 in below code). In the below code the problem is demonstrated, line 65 will cause a segmentation fault.
1 #include <iostream> 2 #include <cstdlib> 3 #include <map> 4 5 using namespace std; 6 7 class MyClass 8 { 9 public: 10 MyClass(int); 11 ~MyClass(); 12 void show(); 13 private: 14 int nr_; 15 }; 16 17 MyClass::MyClas s(int nr) : nr_(nr) 18 { 19 cout << "MyClass: " << nr_ << " constructed" << endl; 20 } 21 22 MyClass::~MyCla ss() 23 { 24 cout << "MyClass: " << nr_ << " destructed" << endl; 25 } 26 27 void MyClass::show() 28 { 29 cout << "Show this MyClass: " << nr_ << endl; 30 } 31 32 typedef map<int, MyClass *> RtdmCyclicTimer Map; 33 34 int main(void) 35 { 36 RtdmCyclicTimer Map cyclicRtdmTimer _; 37 map<int, MyClass *>::const_itera tor cyclicRtdmIt;
I recommend against using raw dummy pointers in an STL container.
I recommend you use a smart pointer like the following: http://axter.com/smartptr
The above smart pointer can be used with std::map, and will
automatically delete the pointee for you.
On 27 Apr 2006 12:40:16 -0700, "Axter" <go****@axter.c om> wrote: I recommend against using raw dummy pointers in an STL container. I recommend you use a smart pointer like the following: http://axter.com/smartptr
The above smart pointer can be used with std::map, and will automaticall y delete the pointee for you.
The problem in the above code is an 'automatically' created NULL
pointer. Is your smart pointer smart enough to avoid that?
Regards,
Roland Pibinger
Andrei Tarassov schreef: 51 // delete 2 AGAIN 52 if (cyclicRtdmTime r_[2]) {
The problem is here. This implicitly adds an element to the map and initializes the pointer with NULL. When you try to dereference that pointer later, you get a segfault.
You could use the following check instead: if (cyclicRtdmTime r_.find(2) != cyclicRtdmTimer _.end()) {
thx yes, now I see.
indeed using find() everything works fine.
It's just that I thought I could use the "operator[]" in a *read-only*
way.
I guess I assumed the operator[] usage in the if statement could never
*write/change* something in the STL map.
Maybe I'm still a bit too C-minded.
thanks all for your insights.
Roland Pibinger wrote: On 27 Apr 2006 12:40:16 -0700, "Axter" <go****@axter.c om> wrote:I recommend against using raw dummy pointers in an STL container. I recommend you use a smart pointer like the following: http://axter.com/smartptr
The above smart pointer can be used with std::map, and will automaticall y delete the pointee for you.
The problem in the above code is an 'automatically' created NULL pointer. Is your smart pointer smart enough to avoid that?
Actually yes.
The smart class has default logic that allows for assignment to a
default object in such cases. See following link, and comments for
smart_ptr<T>::s et_default_obje ct method: http://axter.com/smartptr/classsmart...b02795cf6a8c39
The smart pointer is specifically made to be used with the STL
containers, and it's far safer to use than using raw pointers. 44 if (cyclicRtdmTime r_[2]) { 45 delete cyclicRtdmTimer _[2];
It's good practice to think of operator[] as add/update operator for
non-const maps.
Not to be Not to be used as existence checker.
Regards,
Aman.
--
Posted via Mailgate.ORG Server - http://www.Mailgate.ORG This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Adrian Parker |
last post by:
I have a PHP generated page which displays X many records. Each record has
a checkbox preceding it. The user checks several checkboxes, and hits a
delete button. All the corresponding records will be deleted.
But I'm running into difficulty...
Right now the NAME property of each check box is the primary key of the
corresponding record. Hence if I know which checkboxes are checked, I
simply use DELETE using the NAME value.
|
by: Dino |
last post by:
dear all,
i've created an application for a customer where the customer can upload
..csv-files into a specified ftp-directory. on the server, a php-script,
triggered by a cronjob, reads all the data, imports it into a mySQL database
and deletes the .csv-file after the import.
so far, so good.
but in some cases the cronjobs starts running when the file is not completely
|
by: Travis Spencer |
last post by:
Hello,
I am trying to expose a C++ class to C clients using a C-compatible wrapper
API. While doing so, I hit a little snag. When a C client deletes one on my
classes using the provided delete method, shouldn't the pointer that passed
to DeleteFoo be null when returned?
A simplified example of my project follows.
Thanks a lot and enjoy the rest of the weekend.
|
by: Klemens |
last post by:
The linked table has a bigint in primary key columns.
I've read that service pack 8 on Jet should solve this but it didn't.
On patch1 options I only found to map timestamp to char(26) entry
for similar problems on timestamp fields but nothing for Bigint.
DB2 is UDB8.1 Fix 6 on Win2000
Are there any other solutions?
Thanks
Klemens
|
by: DaveDiego |
last post by:
I've had a user delete one of the client records, I do have a version of
the DB with all records intact before the deletion occured.
Whats the best approach to getting all the related records in each of
the tables? I have about 12 tables to put data back into and multiple
records for each. Would I need to make an append or update query for each
table?
| |
by: jdph40 |
last post by:
On a form in Access 2002, I have a check box called DayCode. In the
AfterUpdate event, I have the following so when the check box is
ticked, the 1st day of the year will populate the text box called
Week1:
If Me!DayCode = True Then
Me!Week1 = DateSerial(Year(Now()), 1, 1)
What I want to do now is if the data entry clerk ticks the check box in
error and then unticks the check box, I want the date to be deleted
|
by: ibiza |
last post by:
Hi SQL fans,
I realized that I often encounter the same situation in a relation
database context, where I really don't know what to do. Here is an
example, where I have 2 tables as follow:
________________________
__________________ | PortfolioTitle
|
|
by: BrianDP |
last post by:
I have a database with a split front end/back end. There is a key
table in the back end called Catalog, and it is sort of a central key
table for all sorts of things. It's a list of all the jobs that have
ever been worked on at our company. Records are getting lost out of
this table, but I have no way of figuring out how they're being
deleted. Records should NEVER be deleted out of this table. They can
be marked as inactive, or...
|
by: Mark |
last post by:
Hi,
I would like to check if my object has been deleted or not, but my
program keeps crashing. Here's the simplified code (in infinite loop)
delete tetromino;
//if(tetromino==NULL)
tetromino = new TetrominoI;
This continuously replaces the tetromino as expected, but if I take
|
by: david720 |
last post by:
Error 3167 Record is deleted
And
Sometimes the main entry form displays a record in the form where all
fields are "#Delete"
Why do we get this error sometimes (about 2 times a week)?
It happens from different users and on different workstations.
Also in this application no records are ever deleted and would be
difficult for a user to delete a record
|
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...
| |
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,...
|
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 captivates audiences and drives business growth.
The Art of Business Website Design
Your website is...
|
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 choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
|
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...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one.
At the time of converting from word file to html my equations which are in the word document file was convert into image.
Globals.ThisAddIn.Application.ActiveDocument.Select();...
|
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...
| |
by: 6302768590 |
last post by:
Hai team
i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |