创建新数组时写入位置时发生访问冲突
Access violation writing location on creation of new array
我正在做家庭作业,班上的老师不允许我们提问。他要求我们试着自己解决这一切,但我在过去的一周里一直在努力让它发挥作用,但它也犯了同样的错误,我不知道为什么。我在谷歌上做了一些搜索,并浏览了SO,寻找任何有类似错误但找不到解决方案的人。
在创建新数组并输入用户输入开始填充新数组之后,它才能正常工作,然后抛出:
6b.exe中0x000B517B处的首次机会异常:0xC0000005:访问写入位置0x00008147的冲突。程序"[4112]6b.exe"已退出,代码为0(0x0)。
#include "stdafx.h"
#include <iostream>
using namespace std;
int* read_data(int& size){
size++;
return &size;
}
void main(){
int size = 0; // size is 0 to start
int max = 10; // set max to 10 to start
float user; //user imputed float number
cout << "Start entering your numbers.n Be sure to hit RETURN between each one.nWhen you are finished, hit 'Q'n";
float *a = new float [max]; //set first array that can be deleted and replaced
do {
//if the array is full, make a new one and replace.
if(size == max){
max = max *2; //double max number
float *b = new float [max]; //create temporary array b
for (int i = 0; i < size; i++){
b[i] = a[i]; //copy old array to temporary
}
delete[] a; //remove old a array.
float *a = new float [max]; //create new a array with the new max, same name for the loop.
//copy new a array to resume filling
for(int i = 0; i< size; i++){
a[i] = b[i];
}
delete[] b; //remove temporary array to free memory.
}
cin >> user; // user inputs the number
a[size] = user; //user input
read_data(size); //increase size by one.
}while (!cin.fail());
size--; //remove one for the entering of Q otherwise it throws off the count.
if (cin.fail()){
cout << "nnYou have finished inputting.n You have imputed " << size << " numbers. nThe inputed numbers are as follows:n";
for(int i=0; i < size; i++){
cout << a[i];
if (i == size -1){
cout << "nn";
}
else {
cout << ", ";
}
}
cout << "nn";
}
system("pause");
}
教练希望基本上每一行都有评论,这就是为什么有这么多评论的原因。
如果有人能帮我,那就太好了。
delete[] a; //remove old a array.
这将删除您在main()
函数的外部作用域中声明的a
数组。
下一行:
float *a = new float [max];
这将在内部作用域中创建一个名为a
的新变量。展望未来,你认为发生在你的原始a
上的事情,在你的main()
开始时声明的,实际上是对另一个a
做的。原始的a
是"隐藏的",因此,当这个范围结束时,您分配的新数组就会泄漏,而您的原始a
数组现在指向未分配的内存。
Hillarity随之而来。
"你对管道的思考越多,就越容易停止排水"-斯科蒂,《星际迷航III》
在分配了新的b
数组并将a
的内容复制到它之后,您真正需要做的就是:
a=b;
您不需要分配另一个a
数组,并将其从b
复制回来,然后删除b
。这样做毫无效果,而且你不经意间犯了一个相当邪恶的错误。。。
相关文章:
- 写入位置0x0000000C时发生访问冲突
- 0xC0000005:访问冲突写入位置0xCDCDCDCD动态分配错误
- 0xC0000005:访问冲突读取位置 0x00000000. 重载 == 运算符的问题
- (此函数用于计算 SMA).在 FA.exe 中0x00509159引发异常: 0xC0000005:访问冲突读取位置0
- 0xC0000005:读取位置0xCDCDCDC1时发生访问冲突
- 0xC0000005:读取位置0xCDCDCDCD时发生访问冲突
- 读取类的析构函数中的位置时发生访问冲突
- 在尝试使用CUDA分配内存时,我遇到了访问冲突写入位置错误
- 创建 2D 数组0xCCCCCCCC访问冲突写入位置
- 0x0F50DF58:0xC0000005:访问冲突读取位置0x0047CA04时未处理的异常
- 在 DLL 中嵌入 Python:Py_DECREF列表对象时访问冲突读取位置
- 在 C 代码中调用 Python 函数时第三次出现访问冲突写入位置错误
- 0xC0000005:访问冲突读取位置0x0000000000000008
- 使用动态数组访问冲突写入位置
- C++访问冲突读取位置0xDDDDDDCD当我尝试删除已更新的数组时
- 使用向量的函数崩溃,调试器说访问冲突读取位置
- vc++ 访问冲突读取位置
- C++ - 智能指针 - 访问冲突读取位置0xDDDDDDDD
- C++访问冲突读取位置错误
- 调用隔离后访问冲突执行位置0x0000000000000000:New()