MyString.exe中0x0FC9E559(ucrtbased.dll)的未处理异常:0xC0000005:访问冲突写入位置0x00000000

时间:2019-03-02 11:27:22

标签: c++ heap-memory

我的字符串类有问题:“ strcpy函数中未处理的异常”。我没有很多指针方面的经验。请给我您的建议。 预先谢谢您!

使用的IDE:Visual Studio 2017

  

MyString.exe中0x0FC9E559(ucrtbased.dll)的未处理异常:   0xC0000005:访问冲突写入位置0x00000000。

MyString.cpp:

#pragma warning(disable:4996)
#include "MyString.h"
#include "cstring"
#include <iostream>
using namespace std;

MyString::MyString()
{
    length = 0;
    content = NULL;
}

MyString::MyString(int length, const char* content) 
{
    this->length = length;
    this->content = new char[this->length + 1];
    strcpy(this->content, content);
}

MyString::MyString(const char* content)
{
    length = strlen(content);
    this->content = new char[length + 1];
    strcpy(this->content, content);
}

void MyString::setLength(int length) 
{
    this->length = length;
}

const int MyString::getLength() 
{
    return length;
}

void MyString::setContent(char* content) 
{
    strcpy(this->content, content); // Unhandled exception !!!
}

const char* MyString::getContent() 
{
    return content;
}

ostream& operator << (ostream& out, const MyString& string)
{

        out << "Content:\n" << string.content << "\n";
        out << "Length:\n" << string.length << "\n";

    return out;
}

const MyString operator+(MyString& string1, MyString& string2)
{
    MyString concatString;
    concatString.setLength(string1.length + string2.length);
    strcat(string1.content, string2.content);
    concatString.setContent(string1.content);

    return concatString;
}

MyString::~MyString()
{
    delete[] content;
}

MyString.h:

#include <iostream>
using namespace std;

class MyString
{
private:
    int length;
    char* content;

public:

    friend ostream& operator << (ostream& out, const MyString& anotherString);

    MyString(); // Constructor fara parametrii
    MyString(int, const char*); // Constructor cu 2 parametrii
    MyString(const char*); // Constructor cu 1 parametru

    friend const MyString operator+(MyString&, MyString&);

    // setters and getters
    void setLength(int);
    const int getLength();
    void setContent(char*);
    const char* getContent();

    // destructor
    ~MyString();
};

Main.cpp:

#include <iostream>
#include "MyString.h"
using namespace std;

int main() {

    MyString string1("---");
    MyString string2("..");

    cout << (string1 + string2);


    system("pause");
    return 1;
}

2 个答案:

答案 0 :(得分:1)

const MyString operator+(MyString& string1, MyString& string2)
{
    MyString concatString;
    concatString.setLength(string1.length + string2.length);
    strcat(string1.content, string2.content);
    concatString.setContent(string1.content);

    return concatString;
}

concatString 被创建为空,而 setLength 仅设置没有(重新)分配 content 的长度,因此您 strcpy setContent

中的空指针

您还需要在 concatString 中而不是在 string1

中复制并合并

例如:

void MyString::setLength(int length) 
{
    if (length > this->length) {
      char * b = new char[length + 1];

      if (this->content != NULL) {
        strcpy(b, this->content);
        delete [] this->content;
      }
      this->content = b;
    }
    this->length = length;
}

const MyString operator+(const MyString& string1, const MyString& string2)
{
    MyString concatString;
    concatString.setLength(string1.length + string2.length);
    strcpy(concatString.content, string1.content);
    strcat(concatString.content, string2.content);

    return concatString;
}

setContent 不能仅仅做一个 strcpy ,例如做得更好

void MyString::setContent(char* content) 
{
  if (content == NULL) {
    if (this->content != NULL) 
      delete [] this->content;
    this->content = NULL;
    this->length = 0;
  }
  else {
    setLength(strlen(content));
    strcpy(this->content, content);
  }
}

这两项更改之后,进行编译和执行:

pi@raspberrypi:/tmp $ g++ -pedantic -Wextra -g MyString.cpp Main.cpp 
In file included from MyString.cpp:2:0:
MyString.h:22:25: warning: type qualifiers ignored on function return type [-Wignored-qualifiers]
     const int getLength();
                         ^
MyString.cpp:41:31: warning: type qualifiers ignored on function return type [-Wignored-qualifiers]
 const int MyString::getLength()
                               ^
In file included from Main.cpp:2:0:
MyString.h:22:25: warning: type qualifiers ignored on function return type [-Wignored-qualifiers]
     const int getLength();

pi@raspberrypi:/tmp $ ./a.out
Content:
---..
Length:
5
sh: 1: pause: not found

valgrind

pi@raspberrypi:/tmp $ valgrind ./a.out
==6134== Memcheck, a memory error detector
==6134== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==6134== Using Valgrind-3.13.0 and LibVEX; rerun with -h for copyright info
==6134== Command: ./a.out
==6134== 
Content:
---..
Length:
5
sh: 1: pause: not found
==6134== 
==6134== HEAP SUMMARY:
==6134==     in use at exit: 0 bytes in 0 blocks
==6134==   total heap usage: 5 allocs, 5 frees, 21,261 bytes allocated
==6134== 
==6134== All heap blocks were freed -- no leaks are possible
==6134== 
==6134== For counts of detected and suppressed errors, rerun with: -v
==6134== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 6 from 3)

要在编译期间没有警告,请不要返回 const int ,而只需返回 int

最好将 length 设为size_t,而不是 int

getLength getContent 可以是 const int getLength() constconst char* getContent() const


正如克里斯托弗(Christophe)在评论中所说,operator+返回字符串的副本,您既未定义副本构造函数,也未定义operator=。当一个类包含指针时,需要定义它们,并且对于最近的C ++, move

答案 1 :(得分:1)

此代码有两个问题。

首先,您需要实现rule of 3,因此还需要提供复制构造函数和赋值运算符。

然后setLength()调整字符串的最大长度,但它无法分配任何内容,因此您可能会创建缓冲区溢出,或者由于nullptr而使用默认构造函数的UB。这就是您的operator+()中发生的情况。

一旦实施了3规则,对operator +的快速修复可能是:

const MyString operator+(MyString& string1, MyString& string2)
{
    MyString concatString(string1.length + string2.length, string1.content);
    strcat(concatString.content, string2.content);

    return concatString;   // but this requires copy constructor to work
}

对于基于长度的构造函数,请确保该长度大于要复制的字符串。因此,您可以断言这一点,或者使用strncpy()