char指针上的C ++错误

时间:2013-04-14 11:32:41

标签: c++ char-pointer

我想在struct中初始化一个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);

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

2 个答案:

答案 0 :(得分:7)

在传递对象之前,需要为这些对象分配内存:

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

作为一般建议不要做这样的typedef,它们非常容易混淆并且容易出错。如果您决定键入一个指针,至少表明它是该类型中的指针,即:typedef struct __String* MyStringPtr

答案 1 :(得分: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_stringright_stringboth_string)。 这就是我猜的原因。

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