首页 > 解决方案 > 坏数组新长度错误未处理异常

问题描述

我不确定我哪里出错了。

我有一个 Movie.h,其中包含所需的所有数据成员和构造函数析构函数和复制构造函数,但我觉得它在我的赋值运算符上失败了,请帮忙

  Movie& Movie::operator=(const Movie& _assign) {
    // Self-assignment check
    if (this == &_assign)
        return *this;

    // Shallow copy non-dynamic data members
    mRuntime = _assign.mRuntime;

    // Deep copy appropriate data members
    mTitle = new char[strlen(_assign.mTitle) + 1];
    strcpy_s(mTitle, strlen(_assign.mTitle) + 1, _assign.mTitle);

    // Deep copy the reviews
    SetStars(_assign.mStars, mNumReviews);

    return *this;
  }

  void Movie::SetStars(const int* _stars, int _numReviews) {
    
    // Allocate array and deep copy
    mStars = new int[_numReviews];

    for (int i = 0; i <= _numReviews; ++i) {
        // Cap reviews between 1-10
        if (_stars[i] > 10)
        {
            mStars[i] = 10;
        }
        else if (_stars[i] < 0)
        {
            mStars[i] = 0;
        }
        else
        {
            mStars[i] = _stars[i];
        }
    }

    // Set the number of reviews
    mNumReviews = _numReviews;
  }

标签: c++arraysassignment-operatorunhandled-exception

解决方案


问题发生在这里:

mStars = new int[_numReviews];


for (int i = 0; i <= _numReviews; ++i) {

具体在这里:

i <= _numReview // this causes you to go out of bounds

将其更改为:

i < _numReview

解决问题

您正在分配_numReview项目。C++ 具有基于 0 的数组索引。元素将从0_numReview - 1

请考虑使用std::stringandstd::vector而不是 c 样式的数组。


推荐阅读