473,387 Members | 1,903 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,387 software developers and data experts.

Segmentation fault in list...

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;

class TestSTL
{
string *_str;

public:
TestSTL() { _str = new string("test"); };
~TestSTL() { cerr << "destruct" << endl; delete _str; }
};
TestSTL.cpp:
#include "TestSTL.h"

int main()
{
list<TestSTL> lst;
lst.push_back(TestSTL());
}

Could U explain to me what's wrong here?

Thanx.
With the best regards
Daniel.
Jul 25 '05 #1
5 3303
saratoga wrote:
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;

class TestSTL
{
string *_str;

public:
TestSTL() { _str = new string("test"); };
~TestSTL() { cerr << "destruct" << endl; delete _str; }
};
TestSTL.cpp:
#include "TestSTL.h"

int main()
{
list<TestSTL> lst;
lst.push_back(TestSTL());
}

Could U explain to me what's wrong here?


You failed to define an appropriate copy constructor. The
compiler-generated copy constructor is generally not appropriate for
classes (like yours) that acquire resources (in this case, by using
new).

Best regards,

Tom

Jul 25 '05 #2
Thomas Tutone wrote:

You failed to define an appropriate copy constructor. The
compiler-generated copy constructor is generally not appropriate for
classes (like yours) that acquire resources (in this case, by using
new).

And an copy-assignment operator. Std containers require both.
Jul 26 '05 #3
Ram
A side comment- Its not a good idea to say something like new string
(unless u are allocating an array of strings). Using std::string can
relieve u of having to take care of memory management.

Best regards
Ram

Jul 26 '05 #4
"Thomas Tutone" <Th***********@yahoo.com> wrote in
news:11**********************@g44g2000cwa.googlegr oups.com:
saratoga wrote:
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;

class TestSTL
{
string *_str;

public:
TestSTL() { _str = new string("test"); };
~TestSTL() { cerr << "destruct" << endl; delete _str; }
};
TestSTL.cpp:
#include "TestSTL.h"

int main()
{
list<TestSTL> lst;
lst.push_back(TestSTL());
}

Could U explain to me what's wrong here?


You failed to define an appropriate copy constructor. The
compiler-generated copy constructor is generally not appropriate for
classes (like yours) that acquire resources (in this case, by using
new).


For the OP:

When the code does push_lst.back, it creates a *copy* of the TestSTL
object you passed (the nameless temporary). Because you didn't specify a
copy constructor, the compiler generated one for you. This compiler-
generated copy constructor does a member-by-member copy (also called
"shallow copy"). So now you have two TestSTL objects, and their _str
members point to the same dynamically allocated string. The object you
created (a temporary) will be destroyed at the end of the push_back
statement, and it will deallocate the string. When the list is destroyed,
it will destroy the stored TestSTL object, which in turn will try to
deallocate the string again.

If you want to store objects in an STL container, it's best to avoid
naked pointer members. If you need a string, you can use std::string. If
you need a lump of memory, you can use std::vector<char>. All STL classes
have proper value semantics; they will take care of the copy operations
that permeate C++.

If you want to keep the naked pointer and still use std::list, you have
two possibilities:

1) Implement the copy constructor and copy assignment operator yourself
to perform a deep copy (allocate another string and copy the original).
This is what std::string does (hint, hint).

2) Do some sort of reference counting.
--
Life is complex, with real and imaginary parts.
Jul 27 '05 #5
saratoga wrote:
I've 'Segmentation fault' in this code. I've found that there are two
calls to destructor.

[snip]

Others have given the specific answer to your question.
For this, and many related questions, you should check
out the FAQ for the group.

http://www.parashift.com/c++-faq-lite/
Socks

Jul 27 '05 #6

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

Similar topics

10
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...
9
by: fudmore | last post by:
Hello Everybody. I have a Segmentation fault problem. The code section at the bottom keeps throwing a Segmentation fault when it enters the IF block for the second time. const int...
7
by: Alexandre | last post by:
Hello, Maybe it's a little OT, but the fact is that I don't necessarly want to know "how to correct?", but "why it happens?" I have a program who "segment fault" (ok, that's "normal"... ;-)...
3
by: Zheng Da | last post by:
Program received signal SIGSEGV, Segmentation fault. 0x40093343 in _int_malloc () from /lib/tls/libc.so.6 (gdb) bt #0 0x40093343 in _int_malloc () from /lib/tls/libc.so.6 #1 0x40094c54 in malloc...
5
by: Fra-it | last post by:
Hi everybody, I'm trying to make the following code running properly, but I can't get rid of the "SEGMENTATION FAULT" error message when executing. Reading some messages posted earlier, I...
27
by: Paminu | last post by:
I have a wierd problem. In my main function I print "test" as the first thing. But if I run the call to node_alloc AFTER the printf call I get a segmentation fault and test is not printed! ...
7
by: pycraze | last post by:
I would like to ask a question. How do one handle the exception due to Segmentation fault due to Python ? Our bit operations and arithmetic manipulations are written in C and to some of our...
3
by: madunix | last post by:
My Server is suffering bad lag (High Utlization) I am running on that server Oracle10g with apache_1.3.35/ php-4.4.2 Web visitors retrieve data from the web by php calls through oci cobnnection...
6
by: DanielJohnson | last post by:
int main() { printf("\n Hello World"); main; return 0; } This program terminate just after one loop while the second program goes on infinitely untill segmentation fault (core dumped) on...
25
by: jbholman | last post by:
I am pretty new to C and doing my first project in C. I actually read almost the entire FAQ, but can't seem to figure out this problem. I have a structure. I have a list of these structures. ...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
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...
0
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,...
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
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,...
0
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...

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.