繁体   English   中英

VS2017社区中的C ++程序崩溃

[英]C++ program crash in VS2017 Community

我试图写简单的课。 但是一开始就遇到了问题。 当我编写构造函数时,1个析构函数和1个显示类方法并在main函数中调用它时,出现了意外错误。 最有趣的是,在调试模式下,在VS2017社区中,错误抛出在不同的地方:一次在构造函数中,另一次在show方法中,最重要的是在主函数中返回0。 那是我的main.cpp

#include "MyScreen.h"

int main()
{
    MyScreen scr = MyScreen(10, 10);
    scr.show();
    char ch;
    std::cin >> ch;
    return 0;
}

这是我的MyScreen类的头文件

#pragma once
#include <iostream>
using std::cout;
class MyScreen
{
public:
    MyScreen();
    MyScreen(int, int, char pc = _filler);
    ~MyScreen();

    void show();
private:
    static const int maxHeight;
    static const int maxWidth;
    static const char _filler;
    int _height;
    int _width;
    char *_wContent;
    int _cursor;
};

和cpp文件

#include "MyScreen.h"

const int  MyScreen::maxHeight = 28;
const int  MyScreen::maxWidth  = 118;
const char MyScreen::_filler   = '#';

MyScreen::MyScreen()
{
    _height = maxHeight;
    _width = maxWidth;
    unsigned length = _height * _width;
    _wContent = new char(length);
    for (int i = 0; i < length; i++)
        _wContent[i] = _filler;
    _cursor = 0;
}

MyScreen::MyScreen(int height, int width, char pc)
{
    _height = height;
    _width = width;
    unsigned length = _height * _width;
    _wContent = new char(length);
    for (int i = 0; i < length; i++)
        _wContent[i] = pc;
    _cursor = 0;
}

MyScreen::~MyScreen()
{
    delete[] _wContent;
    _wContent = 0;
}

void MyScreen::show()
{
    for (int i = 0; i < _height; i++)
    {
        for (int j = 0; j < _width; j++)
            cout << _wContent[i * 10 + j] << i * 10 + j;
        cout << '\n';
    }
}

有我得到的错误描述:

检测到严重错误c0000374 ScreenClass.exe已触发断点。 (xutility文件)

引发异常:读取访问冲突。 ptd为0x264FD5EC。 (fstream文件)

调试错误! 已检测到堆损坏:在0x02ABC5A8的正常块(#152)之后。 点击率检测到应用程序在堆缓冲区结束后写入了内存。

我不明白自己做错了什么? 我尝试在DevC ++中编译并运行此代码,它也会引发错误(返回3221226356),但是在对该代码进行第三次重新编译后,它开始正常工作而没有错误!

这个问题属于VS2017吗? 如果是,那么如何解决?

解决方案:应为方括号:

_wContent = new char[length];

相反,如果使用简单括号,则因为()会分配空间并仅初始化1个值。 但是在不同的IDE中,未定义的行为可能不同(例如在DevC ++中)。 强烈建议使用std::vector<char>以避免可能导致未定义行为的指针操作。

非常感谢Ron,Borgleader和Bo Persson的帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM