473,770 Members | 1,642 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

segmentation fault on delete object (which belongs to some class under a hierarchy)

I have this bug that quite puzzled me. Basically I am having a
segmentation fault on deleting an object, which belongs to a class
which is the result of multiple inheritance from two other classes.
None of the classes actually allocate memory on the heap. I simplified
my code into one piece to show below. I will really appreciate if
someone can tell me where the problem is. I have spent quite some time
on it and felt a bit lost at this point.

the compiler is g++ (GCC 3.3.2 on Mandrake)

Thank you for your help!

Joel
code
--------------
#include <hash_map.h>

typedef union {
long r1;
double r2;
} rank_t;

struct eqstr {
bool operator()(cons t char* s1, const char* s2) const {
return strcmp(s1, s2) == 0;
}
};

typedef struct oety {
double p1;
double p2;
oety():p1(1),p2 (1) {}
static bool change(oety* s_entry);
} oentry;

typedef struct eety {
rank_t rank;
} eentry;

typedef hash_map<char*, eentry*, hash<char*>, eqstr> EType;

typedef struct oeety : public oentry, public eentry {
oeety() {rank.r2 = 1;}
} oeentry;

int main ( int argc, int argv[] ) {
EType* extraInfo = new EType();

eentry* entry1;
entry1 = new oeentry();
char * s_name = new char[2];
s_name[0] = 'a';
s_name[1] = '\0';
(*extraInfo)[s_name] = entry1;

entry1 = new oeentry();
s_name = new char[2];
s_name[0] = 'b';
s_name[1] = '\0';
(*extraInfo)[s_name] = entry1;

EType::iterator itr = extraInfo->begin();

cout << "point 1" << endl;
delete itr->second; //segmentation fault!!!!!!!!!! !!!!!
cout << "point 2" << endl;

return 0;
}
---------------

result:
a.out


point 1
Segmentation fault
Jul 22 '05 #1
4 2171
Joel wrote:
I have this bug that quite puzzled me. Basically I am having a
segmentation fault on deleting an object, which belongs to a class
which is the result of multiple inheritance from two other classes.
None of the classes actually allocate memory on the heap. I simplified
my code into one piece to show below. I will really appreciate if
someone can tell me where the problem is. I have spent quite some time
on it and felt a bit lost at this point.

Your code is deleting a different object than was constructed. This is
the cause of your segfault.


code
--------------
#include <hash_map.h>
has_map is not standard but is planned to be.

Anyhow - you should try to use the non deprecated header.

#include <ext/hash_map>
#include <iostream>

// gcc requires using namespace __gnu_cxx for hash containers

using namespace __gnu_cxx;
using namespace std;

typedef union {
long r1;
double r2;
} rank_t;
this is easier to read than this whole typedef nonsense.

union rank_t {
long r1;
double r2;
};


struct eqstr {
bool operator()(cons t char* s1, const char* s2) const {
return strcmp(s1, s2) == 0;
}
};

typedef struct oety {
double p1;
double p2;
oety():p1(1),p2 (1) {}
static bool change(oety* s_entry);
} oentry;


typedef struct eety {
rank_t rank;
} eentry;

typedef hash_map<char*, eentry*, hash<char*>, eqstr> EType;

typedef struct oeety : public oentry, public eentry {
oeety() {rank.r2 = 1;}
} oeentry;

int main ( int argc, int argv[] ) {
EType* extraInfo = new EType();

eentry* entry1;
entry1 = new oeentry();
Allocating an oeety object and assigning it to a eety pointer. This
means that the pointer that is stored is not the pointer that was
returned by new.
char * s_name = new char[2];
s_name[0] = 'a';
s_name[1] = '\0';
(*extraInfo)[s_name] = entry1;

entry1 = new oeentry();
s_name = new char[2];
s_name[0] = 'b';
s_name[1] = '\0';
(*extraInfo)[s_name] = entry1;

EType::iterator itr = extraInfo->begin();

cout << "point 1" << endl;
delete itr->second; //segmentation fault!!!!!!!!!! !!!!!


Attempting to delete a pointer that was not returned by new ...

2 solutions - use virtual destructors for the base classes or design it
differently.
Jul 22 '05 #2

"Joel" <yb****@gmail.c om> wrote in message
news:79******** *************** ***@posting.goo gle.com...
I have this bug that quite puzzled me. Basically I am having a
segmentation fault on deleting an object, which belongs to a class
which is the result of multiple inheritance from two other classes.
None of the classes actually allocate memory on the heap. I simplified
my code into one piece to show below. I will really appreciate if
someone can tell me where the problem is. I have spent quite some time
on it and felt a bit lost at this point.

It's a simple enough problem see below.
the compiler is g++ (GCC 3.3.2 on Mandrake)

Thank you for your help!

Joel
code
--------------
#include <hash_map.h>

typedef union {
long r1;
double r2;
} rank_t;
In C++ we prefer

union rank_t {
long r1;
double r2;
};

You are still programming as if you are writing C. You also might want to
look up 'anonymous unions' in your favourite C++ book.

struct eqstr {
bool operator()(cons t char* s1, const char* s2) const {
return strcmp(s1, s2) == 0;
}
};

typedef struct oety {
double p1;
double p2;
oety():p1(1),p2 (1) {}
static bool change(oety* s_entry);
} oentry;
Again

struct oentry {
double p1;
double p2;
oety():p1(1),p2 (1) {}
static bool change(oety* s_entry);
};

And having the struct name different from the typedef name is REALLY WIERD
and therefore a bad thing.

typedef struct eety {
rank_t rank;
} eentry;
Ditto. And this is the place where using an anonymous union would simplify
your code a little. Delete rank_t above and write this

struct eentry {

union {
long r1;
double r2;
};
};

Then you don't have to write

rank.r2 = 1;

you can just write

r2 = 1;

typedef hash_map<char*, eentry*, hash<char*>, eqstr> EType;

typedef struct oeety : public oentry, public eentry {
oeety() {rank.r2 = 1;}
} oeentry;

int main ( int argc, int argv[] ) {
EType* extraInfo = new EType();

eentry* entry1;
entry1 = new oeentry();
char * s_name = new char[2];
s_name[0] = 'a';
s_name[1] = '\0';
(*extraInfo)[s_name] = entry1;

entry1 = new oeentry();
s_name = new char[2];
s_name[0] = 'b';
s_name[1] = '\0';
(*extraInfo)[s_name] = entry1;

EType::iterator itr = extraInfo->begin();

cout << "point 1" << endl;
delete itr->second; //segmentation fault!!!!!!!!!! !!!!!
cout << "point 2" << endl;

return 0;
}


OK here the real point, there is a rule in C++ that you cannot delete an
object through a pointer to its base class unless that base class has a
virtual destructor. Add a virtual destructor to oentry and eentry and you
will be OK. What this means is that any class from which you are considering
deriving another class (now or in the future) should be given a virtual
destructor.

john

BTW is there nay reason not to use std::strings in the code above. Better
than all those char pointers.

john
Jul 22 '05 #3
Thanks for all the reply. I guess I did not realize that destructors
behave so much differently than default constructors. I kind of thought
that there is some "default" destructor, which is called automatically
in the base classes (like default constructors, when you do not have any
non-default defined). Apparently this is not the case, which makes sense
too since you can not really have any non-default destructors.

The project came from C and gradually is being added things c++. Quite
some things, including some coding habbits, still looks like c. Thanks
for the criticizements too.
Jul 22 '05 #4

"Joel" <yb****@gmail.c om> wrote in message
news:ck******** **@daisy.noc.uc la.edu...
Thanks for all the reply. I guess I did not realize that destructors
behave so much differently than default constructors. I kind of thought
that there is some "default" destructor, which is called automatically in
the base classes (like default constructors, when you do not have any
non-default defined). Apparently this is not the case, which makes sense
too since you can not really have any non-default destructors.


There is a default destructor, and very useful it is too. But it is not a
virtual destructor. When you delete an object through a pointer to a base
class the base class needs a *virtual* destructor.

john
Jul 22 '05 #5

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

Similar topics

10
4489
by: Vishal Grover | last post by:
Hello Everyone, I am seeing a certain behaviour which I find strange, and am curious to get an explanation to it. I have the following program. #include <iostream> #include <cstdlib> using namespace std;
18
2659
by: bumps | last post by:
Guys, I am getting segmentation fault while I am trying to open a file in a small function. int PingSamplesList::saveListElements (char *outputFileString) { PingSampleElement *tmpPtr; int rc = 0; ofstream outFile;
3
5210
by: mblome | last post by:
Hi everybody! I came across a very strange problem with stl vectors during developement of a mesh creation program. As the program is quite large I can only post small parts of it. Basically I have a std::vector<SPoly> xtop; where SPoly simply is: struct SPoly { int start, end;
5
3326
by: saratoga | last post by:
Hi, all! I've 'Segmentation fault' in this code. I've found that there are two calls to destructor. TestSTL.h: #include <list> #include <string> #include <iostream> using namespace std;
8
1625
by: ChristophK | last post by:
Hallo, this is my first post and I hope I'm doing well, but if not, please let me know. My problem: First all classes and a main-file (I simplified everything to get to the core of the problem): /*---------------- start of code ---------------------------*/
2
5145
by: pragtideep | last post by:
Kindly help me explain the behaviour of defult copy constructor . Why the destructor is freeing the SAME memory twice , though it was allocated just once . #include<iostream> using namespace std; class var_array { private: int *data; // The data
6
10464
by: IanWright | last post by:
I've got a segmentation fault problem and am wondering if anyone can help me. I'll apologise now for the fact that I've about a week experience using C++, but I'll try my best to follow any replies :) Firstly I'm developing in C++ on a Linux machine (using g++ compiler). My application iterates through a process around about 120 times during testing. It appears that I randomly receive segmentation faults during one of these iterations...
10
12517
by: H.S. | last post by:
Hello, I have class in which I am allocating space for a double array in the constructor. I use the double array twice in one of the methods and then delete that array in the class's destructor. Now, that delete operation is giving me a segmentation fault. If I move the allocation and deletion of the pointer within the method where the pointer is being is used, it works okay ... but then another pointer gives a segmentation fault in...
3
3921
by: jr.freester | last post by:
I have created to classes Matrix and System. System is made up of type matrix. ---------------------------------------------------------------------------------- class Matrix { private: int row, col; double *data public: Matrix(const int& M, const int& N): row(M), col(N)
0
9595
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
9432
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
10232
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...
0
10059
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 captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9873
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 choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8891
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 launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5313
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
5454
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2822
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.