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 12 1819 yp*********@ind iatimes.com wrote: strvector(char * s) { cstr = new char[strlen(s)+1]; strcpy(cstr,s); } ~strvector() { delete str;
If you new[], you need to delete[].
}
Also, read about "the Rule of Three".
V
>If you new[], you need to delete[].
Still its crashing..Also i tried to put the copy constructor but no
improvement..st ill crashing..The code will run fine only when i remove
the destructor and will not release the memory held by cstr..
regards,
Yogesh yp*********@ind iatimes.com wrote: If you new[], you need to delete[].
Still its crashing..Also i tried to put the copy constructor but no improvement..st ill crashing..The code will run fine only when i remove the destructor and will not release the memory held by cstr..
regards, Yogesh
The rule of three states that you need a destructor, copy constructor
and assignment operator.
If it is still crashing then post all the code. The bug is almost
certainly in the code for your copy constructor or assignment operator.
john
John, as per your suggestion i tried to put copy constructor,
assignment operator and destructor..the problem got worst..it can't
even compile..
below is the code
////////////////////////////////// code starts
////////////////////////////////
#include <iostream.h>
#include "string"
#include "vector"
using namespace std;
class strvector
{
char * cstr;
public:
strvector()
{
}
strvector(strve ctor & s)
{
cstr = new char[strlen(s.cstr) + 1];
strcpy(cstr,s.c str);
}
strvector(char * s)
{
cstr = new char[strlen(s)+1];
strcpy(cstr,s);
}
strvector & operator =(strvector & s)
{
cstr = new char[strlen(s.cstr) + 1];
strcpy(cstr,s.c str);
return *this;
}
char * getcstr()
{
return cstr;
}
~strvector()
{
delete []cstr;
}
/* release()
{
delete cstr;
}
*/
};
void main()
{
vector<strvecto r> vec;
strvector str("one");
vec.push_back(s tr);
// str.release();
//cout<<vec[0].getcstr();
}
////////////////////////////////// code ends
//////////////////////////////////
and below are the compile errors
--------------------Configuration: Cpp2 - Win32
Debug--------------------
Compiling...
Cpp2.cpp
c:\program files\microsoft visual studio\vc98\inc lude\xutility(3 9) :
error C2679: binary '=' : no operator defined which takes a right-hand
operand of type 'const class strvector' (or there is no acceptable
conversion)
c:\program files\microsoft visual studio\vc98\inc lude\vector(170 ) : see
reference to function template instantiation 'void __cdecl
std::fill(class strvector *,class strvector *,const class strvector &)'
being compiled
c:\program files\microsoft visual studio\vc98\inc lude\xmemory(34 ) :
error C2558: class 'strvector' : no copy constructor available
c:\program files\microsoft visual studio\vc98\inc lude\xmemory(66 ) : see
reference to function template instantiation 'void __cdecl
std::_Construct (class strvector *,const class strvector &)' being
compiled
Error executing cl.exe.
Cpp2.obj - 2 error(s), 0 warning(s)
regards,
Yogesh Joshi yp*********@ind iatimes.com wrote: John, as per your suggestion i tried to put copy constructor, assignment operator and destructor..the problem got worst..it can't even compile..
You need to get familiar with the concept of "const-correctness". See
my notes inline with the code.
below is the code ////////////////////////////////// code starts //////////////////////////////// #include <iostream.h> #include "string" #include "vector"
using namespace std;
class strvector { char * cstr;
public: strvector() { } strvector(strve ctor & s)
strvector(strve ctor const & s)
{ cstr = new char[strlen(s.cstr) + 1]; strcpy(cstr,s.c str); }
strvector(char * s)
strvector(char const * s)
{ cstr = new char[strlen(s)+1]; strcpy(cstr,s); }
strvector & operator =(strvector & s)
strvector & operator =(strvector const & s)
{ cstr = new char[strlen(s.cstr) + 1]; strcpy(cstr,s.c str); return *this;
}
char * getcstr() { return cstr; }
~strvector() { delete []cstr; } /* release() { delete cstr; } */ };
void main()
int main
{ vector<strvecto r> vec;
strvector str("one"); vec.push_back(s tr); // str.release();
//cout<<vec[0].getcstr(); } ////////////////////////////////// code ends [..]
And spend some time reading the FAQ, it will help tremendously.
V yp*********@ind iatimes.com wrote: John, as per your suggestion i tried to put copy constructor, assignment operator and destructor..the problem got worst..it can't even compile.. below is the code ////////////////////////////////// code starts //////////////////////////////// #include <iostream.h> #include "string" #include "vector"
Should be
#include <iostream>
#include <string.h>
#include <vector> using namespace std;
class strvector { char * cstr;
public: strvector() { }
This is wrong because cstr will be garbage and you will end up deleteing
a garbage pointer. At least you should do
strvector()
{
cstr = 0;
}
strvector(strve ctor & s)
Should be,
strvector(const strvector & s)
{ cstr = new char[strlen(s.cstr) + 1]; strcpy(cstr,s.c str); }
strvector(char * s) { cstr = new char[strlen(s)+1]; strcpy(cstr,s); }
strvector & operator =(strvector & s)
Should be
strvector & operator =(const strvector & s)
You cannot get by in C++ without understanding const.
{ cstr = new char[strlen(s.cstr) + 1]; strcpy(cstr,s.c str); return *this;
This leaks memory. Try this
if (&s != this)
{
delete[] cstr;
cstr = new char[strlen(s.cstr) + 1];
strcpy(cstr,s.c str);
}
return *this;
}
char * getcstr() { return cstr; }
~strvector() { delete []cstr; } /* release() { delete cstr; } */ };
void main() { vector<strvecto r> vec;
strvector str("one"); vec.push_back(s tr); // str.release();
//cout<<vec[0].getcstr(); } ////////////////////////////////// code ends //////////////////////////////////
Now for me it compiles and runs without errors.
john yp*********@ind iatimes.com wrote in news:1127943189 .045541.187280
@o13g2000cwo.go oglegroups.com: John, as per your suggestion i tried to put copy constructor, assignment operator and destructor..the problem got worst..it can't even compile.. below is the code
Comments inline:
////////////////////////////////// code starts ////////////////////////////////
// Ahem... <iostream.h> is non-Standard
// use <iostream> #include <iostream.h> #include "string" #include "vector"
using namespace std;
class strvector { char * cstr;
public: strvector()
: cstr(0) // Initialize the pointer to 0 { } strvector(strve ctor & s)
// This isn't a Copy Constructor (or at least
// not a normal one.... you should have:
strvector(const strvector & s) { cstr = new char[strlen(s.cstr) + 1]; strcpy(cstr,s.c str); }
strvector(char * s) { cstr = new char[strlen(s)+1]; strcpy(cstr,s); }
strvector & operator =(strvector & s) { cstr = new char[strlen(s.cstr) + 1]; strcpy(cstr,s.c str); return *this;
}
char * getcstr() { return cstr; }
~strvector() { delete []cstr; } /* release() { delete cstr; } */ };
void main() { vector<strvecto r> vec;
strvector str("one"); vec.push_back(s tr); // str.release();
//cout<<vec[0].getcstr(); } ////////////////////////////////// code ends ////////////////////////////////// and below are the compile errors
--------------------Configuration: Cpp2 - Win32 Debug-------------------- Compiling... Cpp2.cpp c:\program files\microsoft visual studio\vc98\inc lude\xutility(3 9) : error C2679: binary '=' : no operator defined which takes a right-hand operand of type 'const class strvector' (or there is no acceptable conversion) c:\program files\microsoft visual studio\vc98\inc lude\vector(170 ) : see reference to function template instantiation 'void __cdecl std::fill(class strvector *,class strvector *,const class strvector &)' being compiled c:\program files\microsoft visual studio\vc98\inc lude\xmemory(34 ) : error C2558: class 'strvector' : no copy constructor available
As above.. you don't have a proper copy constructor...
c:\program files\microsoft visual studio\vc98\inc lude\xmemory(66 ) : see reference to function template instantiation 'void __cdecl std::_Construct (class strvector *,const class strvector &)' being compiled Error executing cl.exe.
yes..i could compile the code and ran it without fail..
Thanks Victor,John and Adre!!!
Thanks and Regards,
Yogesh Joshi
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. This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
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) {}
|
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!
|
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,
|
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...
|
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...
| |
by: Thomas |
last post by:
I am compiling with g++ the fol. class:
template<typename E>
class C_vector_ : public std::vector<E>
{
private:
|
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...
|
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...
|
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.
|
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: 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...
|
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: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |
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...
| |