473,811 Members | 2,706 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

class with destructor inside a vector...?

Hello all,
I have encountered with following strange problem.
I am coding in C++ and using VC++ 6 compiler.

I have a class strvector containing char * cstr as a private member
and i have defined its destructor for releasing memory hold by cstr.

In main i created a vector<strvecto r>
and whenever i put a object of strvector inside this vector the program
crashes.

The complete program is as follows
/////////////////////////////////////////
#include <iostream.h>
#include "string"
#include "vector"

using namespace std;

class strvector
{
char * cstr;

public:

char * getcstr()
{
return cstr;
}
strvector(char * s)
{
cstr = new char[strlen(s)+1];
strcpy(cstr,s);
}
~strvector()
{
delete str;
}
/*release()
{
delete cstr;
}*/
};

void main()
{
vector<strvecto r> vec;

strvector str("one");
vec.push_back(s tr);//The program will crash
//str.release();

//cout<<vec[0].getcstr();//will print a garbage values.
}
///////////////////////////////////
If i remove the destructor and define a separate member function
release for releasing the memory,the cout statement will print the
garbase value.

Will someone please tell me what is going wrong in the above program
even if i am following a good programmering approach.(using destructor
etc.)?

Regards,
Yogesh Joshi

Sep 28 '05
12 1820
Just out of curiosity. I tried to run the original code submitted by
Yogesh on Linux platform and it seems to work fine. I was wondering if
somebody could throw some light on that issue.

Sep 29 '05 #11
kamit wrote:
Just out of curiosity. I tried to run the original code submitted by
Yogesh on Linux platform and it seems to work fine. I was wondering if
somebody could throw some light on that issue.


Yogesh's original code freed the same memory twice. The pointer str.cstr
would get freed twice, once when the vector was destroyed and once when
variable str was destroyed. This is because without a copy constructor
the str.cstr pointer would just be copied unchanged into the vector.
Adding a proper copy constructor fixed this problem.

But freeing the same memory twice does not necessarily mean that your
program will crash. It is an exampe of what C++ calls 'undefined
behaviour'. This means that C++ doesn't know how to handle the situation
and *anything* could happen. Yogesh saw a crash on his system, but you
didn't. That's OK, undefined behaviour means anything could happen.
Obviously if you want your programs to work you don't want undefined
behaviour, but just because you do have undefined behaviour doesn't mean
that your programs won't work. This is one thing that makes debugging
C++ tricky.

john
Sep 29 '05 #12
thanks for the feedback john. I really appreciate it.

Sep 29 '05 #13

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

Similar topics

5
8104
by: Bruce Lee Roy | last post by:
Hi, I am using visual studio.net and I am having problems using this bit of code when I create an instance, //////////////////////////////////////////// template<class T> class matrix : public vector<T> { public: matrix(size_t h, size_t w) : vector(h*w), width(w) {}
3
1335
by: alexhong2001 | last post by:
When design a class, should always make it "derivable" as a base class? Is there really a situation that the designed class not "derivable"? When should make a member "protected"? Only when allowing the derived class(es) directly access it? Should destructor always be virtual? Thanks for your comments!
11
1928
by: Brian | last post by:
Dear Programmers, I have a class with a pointer to an array. In the destructor, I just freed this pointer. A problem happens if I define a reference to a vector of this kind of class. The destruction of the assigned memory seems to call the class destructor more than once. I don't know the reason or whether I used the vector class correctly. Attached is my program. Thanks for your help. Regards,
3
3763
by: Hamilton Woods | last post by:
Diehards, I developed a template matrix class back around 1992 using Borland C++ 4.5 (ancestor of C++ Builder) and haven't touched it until a few days ago. I pulled it from the freezer and thawed it out. I built a console app using Microsoft Visual C++ 6 (VC++) and it worked great. Only one line in the header file had to be commented out. I built a console app using Borland C++ Builder 5. The linker complained of references to...
2
2976
by: maynard | last post by:
I have defined a template class (tree data structure) that uses dynamic memory and has properly implemented ctor's, dtor and assignment operator. I can observe the address of my tree object prior to the destructor being called, and then the address once inside the destructor...they're different! The following calls are on the stack between the call to my destructor and the actual destructor itself: `eh vector destructor iterator'(void...
7
2538
by: Thomas | last post by:
I am compiling with g++ the fol. class: template<typename E> class C_vector_ : public std::vector<E> { private:
3
2315
by: Stephen Torri | last post by:
Below is a class that is suppose to represent a segment of memory or a contents of a binary image (e.g. ELF executable). I have started to read Modern C++ Design and thought the best way to ensure I was understanding the chapter on policy classes was to attempt to apply them to my project. I understand the general concept of policies but I lack the knowledge and wisdom of how to identify them in an existing project. So I figured to get an...
15
3541
by: Juha Nieminen | last post by:
I'm sure this is not a new idea, but I have never heard about it before. I'm wondering if this could work: Assume that you have a common base class and a bunch of classes derived from it, and you want to make a deque which can contain any objects of any of those types. Normally what you would have to do is to make a deque or vector of pointers of the base class type and then allocate each object dynamically with 'new' and store the...
1
2529
by: Rune Allnor | last post by:
Hi all. I am sure this is an oldie, but I can't find a useful suggestion on how to solve it. I have a class hierarchy of classes derived from a base class. I would like to set up a vector of smart pointers to the base class, and access the virtual functions of any class in the hierarchy through the virtual functions.
0
10653
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
10395
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...
1
10408
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,...
0
9211
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...
1
7674
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
6895
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();...
0
5564
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
5700
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
3027
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.