Reputation: 29
#include <iostream>
using namespace std;
defining class
class fancyString {
private:
char *content;
bool flag_bold;
bool flag_italics;
public:
fancyString(){
content="";
flag_bold= false;
flag_italics=false;
}
in both functions I'm asked to use the old fashioned calloc
fancyString(char* cntnt){
content=(char *) calloc(strlen(cntnt)+1, sizeof(char*));
Usually the strcpy is the main reason of the crash
strcpy(cntnt,content);
}
fancyString(fancyString & f1){
content=(char *) calloc(strlen(f1.content)+1, sizeof(char*));
Usually the strcpy is the main reason of the crash
strcpy(f1.content,content);
flag_bold=f1.flag_bold;
flag_italics=f1.flag_italics;
}
friend ostream& operator<<(ostream& os, const fancyString& FS){
os<<"string is "<<FS.content<<endl<<"bold status is "<<FS.flag_bold<<endl<<"italics status is "<<FS.flag_italics<<endl;
return os;
}
~fancyString(){
cout << "Destroying the string\n";
if ( content != NULL )
free (content);
}
};
main function
int main(int argc, const char * argv[]) {
fancyString fs1 ("First Example");
fancyString fs2(fs1);
cout<<fs2;
return 0;
}
Upvotes: 0
Views: 278
Reputation: 51815
You have the arguments to the strcpy
calls the wrong way round! See the definition on cppreference:
char * strcpy ( char * destination, const char * source );
So, in your your first constructor, the call:
strcpy(cntnt,content);
is attempting to copy the newly-allocated buffer into the passed argument, which is actually a (constant) string literal:
int main(int argc, const char * argv[]) {
fancyString fs1 ("First Example");
//...
NOTES based on suggestions made in the comments:
(1) Note that, in your calloc
call - which is allocating an 'array' of char
, the elements' size is sizeof(char)
not sizeof(char*)
(which would be appropriate for an 'array' of pointers). Use:
content = (char *) calloc(strlen(cntnt)+1, sizeof(char));
and similarly in the copy constructor.
(2) Assuming that your first constructor is never intended to modify the string given as its argument, you should really specify it as const
:
fancyString(const char* cntnt){
//...
(This would have flagged the error of having the strcpy
arguments wrong!)
Please feel free to ask for further clarification and/or explanation.
Upvotes: 4