c++ - 坏数组新长度错误未处理异常
问题描述
我不确定我哪里出错了。
我有一个 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;
}
解决方案
问题发生在这里:
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::string
andstd::vector
而不是 c 样式的数组。
推荐阅读
- sql - 获取最新更改的信息
- android - 使用导航架构向上导航而不重新加载片段
- python - 需要另一个静态方法的 Python 类静态方法
- typescript - 为什么这个 TypeScript 类型会产生一个类似数组的结构,虽然它看起来像一个类似对象的类型?
- vue.js - Vuetify vflex align-self-end 不起作用
- apache-kafka - 是否可以在 Kafka 中创建一个日志压缩主题,其中最旧的值通过压缩保留,用于分析目的?
- python - 除了 __name__ 之外,在 Python 中的程序执行时设置了哪些变量?
- fortran - 使用具有可分配长度的字符变量的 Fortran 程序在编译时总是显示警告
- html - Spring Boot 不检测 css 和图像
- python - Python 3.6 环境:ImportError:没有名为 http.client 的模块