未处理的内存异常
Unhandled Memory Exception
我正在开发一个程序,该程序根据患者的ID号和血压读数读取一组数据。然后,程序将所有读数相加并得出平均值。然后,它将显示该平均值。这是我到目前为止的程序:
#include <iostream>
#include <string>
#include <conio.h>
#include <fstream>
using namespace std;
int main()
{
//Initialize Required Variables For Program
int patientCount;
string id;
string rHowMany; //String To Read From File
int howMany;
int howManyCount;
int avg = 0;
int avg2;
string line;
int number_lines = 0;
ifstream reader ("data.txt"); //Open The Data File To Be Read From
patientCount = 0;
while (getline(reader, line))
{
number_lines += 1;
}
//getline(reader, id); //Get the patients ID
//getline(reader, rHowMany); //Get How Many BP Records The Patient Has
for (number_lines; number_lines > 0; number_lines--)
{
reader >> id;
reader >> rHowMany;
howMany = stoi(rHowMany);
howManyCount = howMany;
patientCount += 1;
cout << "Patient ID: " + id;
for (howManyCount; howManyCount > 0; howManyCount--)
{
reader >> avg2;
avg = avg + avg2;
}
}
cout << avg;
cout << "n";
cout << howMany;
avg = avg / howMany;
cout << "n";
cout << avg;
_getch();
return 0;
}
当我运行程序时,出现此错误:
在血压.exe的 0x756DB727 处未处理的异常:Microsoft C++异常:内存位置 0x0042F794 处的 std::invalid_argument。
我不太确定这意味着什么,但它打开了一个我以前从未见过的代码列表。就像我说的,我不确定为什么它会抛出这个错误,或者错误意味着什么,但如果有人可以帮助我,我将不胜感激。
这一行:
cout << "Patient ID: " + id;
是有缺陷的。您正在尝试将id
附加到"患者 ID:",但事实并非如此。
字符串文本"患者 ID:"实际上是指向字符序列(即数组)的指针。使用加号时,是在字符序列的内存地址和 id 之间执行指针算术。如果 id 大于字符串的长度,这可能会导致程序尝试访问无效位置。
要解决此问题,只需通过对 <<
运算符进行两次单独的调用,在序列后打印 id:
cout << "Patient ID: " << id; // no +
相关文章:
- 从构造函数抛出异常时如何克服内存泄漏
- 是否值得降低我的代码的可读性,以便在出现内存不足错误时提供异常安全性?
- 我们应该在抛出异常之前取消分配内存吗
- 未找到匹配的运算符删除;如果初始化引发异常,内存将不会被释放
- 内存位置出现Microsoft C++异常:std::out_of_range
- C++中的内存分配(引发异常:读取访问冲突)
- 提升进程间共享内存open_or_create每次都会引发异常
- 错误 在测试.exe 0x76C9FD62时出现未经处理的异常:Microsoft C++异常:内存位置0x006FF8
- 从构造函数内存泄漏引发异常
- 从内存导入密钥时加密++ BERDecode异常?
- 当有大量内存分配时,如何处理C++编程中的异常
- 存在内存访问异常,但我不确定我的代码中出了什么问题
- 内存碎片是否导致内存异常
- cv:内存位置的异常 - 运行 openCV 代码 Visual Studio 2013 & Visual Studio 2017 - Windows 7
- 返回内存异常错误的矢量
- 如果在构造函数中发生异常,如何释放动态内存
- Microsoft C++异常runtime_error在内存位置(代码 0x75A818A2)
- 位置处未处理的异常:内存位置处的Microsoft C++异常:std::length_error
- 在 1.exe 中0x77e4bef7时未处理的异常:Microsoft C++异常:内存位置 0x0012fb8c 处
- 0x771515ee Microsoft C++异常时未处理的异常:内存位置 0x0049f904 处的 std::ba