C ++ error in char pointer

I want to initialize a char * string inside a structure.

this is struct:

typedef struct __String { char* data; // C-string data, unsigned* copyRef; // number of copy reference, delete only when the copyRef is 0 bool isACopy; // this boolean is true when *data is a ref to an other MyString __String () { data = 0; isACopy = false; copyRef = new unsigned(); *copyRef = 0; return; } void addCopyRef() { *copyRef++; } void removeCopyRef() { *copyRef--; } } *MyString; 

and this is where chrash is ..

 void Initialize(MyString& string){ string->data = new char[LENGHT]; string->data[0] ='\0'; // this generate an error! string->addCopyRef(); } 

this is the main thing:

 MyString left_string, right_string, both_string; Initialize(left_string); Initialize(right_string); Initialize(both_string); 

the first is going well, the second is not .. might like it, can you help me understand where the problem is? thanks!

+4
source share
2 answers

You need to allocate memory for objects before transferring them as follows:

 MyString left_string = new __String(); Initialize(left_string); 

As the general proposal does not make such typedefs, they are very confusing and error prone. If you decide on a typedef pointer, at least give it a pointer to a type, typedef struct __String* MyStringPtr .: typedef struct __String* MyStringPtr .

+7
source
 typedef struct __String { char* data; // C-string data, unsigned* copyRef; // number of copy reference, // delete only when the copyRef is 0 bool isACopy; // this boolean is true when *data // is a ref to an other MyString __String () { data = 0; isACopy = false; copyRef = new unsigned; *copyRef = 0; return; } void addCopyRef() { *copyRef++; } void removeCopyRef() { *copyRef--; } } *MyString; void Initialize(MyString& string){ string->data = new char[100]; string->data[0] ='\0'; // this generate an error! string->copyRef = new unsigned(); string->addCopyRef(); } int main() { MyString mystring = new struct __String; Initialize(mystring); } 

I tested it without errors. from g ++ to linux. I think you are better

  • at least provide an error message here
  • and your compiler and the platform you are working on.

I checked again with another main () below.

 int main() { MyString mystring = new struct __String; MyString mystring1 = new struct __String; MyString mystring2 = new struct __String; Initialize(mystring); Initialize(mystring1); Initialize(mystring2); } 

There is no error using this test code. I think you skipped creating the object pointed to by mystring (In your code, left_string , right_string , both_string ). This will probably be the reason.

And this code creates a memory leak from the constructor. In this state of code, a constructor is not needed.

+2
source

All Articles