4

我想在结构内初始化一个 char* 字符串。

这是结构:

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[LENGHT];
    string->data[0] ='\0'; // this generate an error!
    string->addCopyRef();
}

这是主要的:

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

第一个进展顺利,第二个没有..请你帮我理解问题出在哪里?谢谢!

4

2 回答 2

7

You need to allocate memory for the objects before passing them like this:

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

As a general suggestion don't do such typedefs, they are very confusing and are error prone. If you do decide to typedef a pointer at least indicate it's a pointer in the type, i.e: typedef struct __String* MyStringPtr.

于 2013-04-14T11:46:37.250 回答
2
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);
}

我这样测试没有任何错误。在 Linux 上使用 g++。我觉得你最好

  • 至少在这里提供错误信息
  • 以及您使用的编译器和平台。

我用下面的另一个 main() 再次测试。

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

使用此测试代码,没有错误。mystring我认为您错过了实例化由(在您的代码中left_string,,,,right_string)指向的对象both_string。我猜这就是原因。

这段代码会从构造函数中产生内存泄漏。在这种代码状态下,不需要构造函数。

于 2013-04-14T11:50:42.683 回答