c++ - Access violation writing location on creation of new array -
i working on homework assignment , instructor class not allow ask questions. demands try figure out on our own have been trying work past week , throwing same error , have no clue why. have done google searches , browsed has similar error , couldn't find solution.
it works fine until after creates new array , user input entered start filling new array, throws :
first-chance exception @ 0x000b517b in 6b.exe: 0xc0000005: access violation writing location 0x00008147. program '[4112] 6b.exe' has exited code 0 (0x0).
#include "stdafx.h" #include <iostream> using namespace std; int* read_data(int& size){ size++; return &size; } void main(){ int size = 0; // size 0 start int max = 10; // set max 10 start float user; //user imputed float number cout << "start entering numbers.\n sure hit return between each one.\nwhen finished, hit 'q'\n"; float *a = new float [max]; //set first array can deleted , replaced { //if array full, make new 1 , replace. if(size == max){ max = max *2; //double max number float *b = new float [max]; //create temporary array b (int = 0; < size; i++){ b[i] = a[i]; //copy old array temporary } delete[] a; //remove old array. float *a = new float [max]; //create new array new max, same name loop. //copy new array resume filling for(int = 0; i< size; i++){ a[i] = b[i]; } delete[] b; //remove temporary array free memory. } cin >> user; // user inputs number a[size] = user; //user input read_data(size); //increase size one. }while (!cin.fail()); size--; //remove 1 entering of q otherwise throws off count. if (cin.fail()){ cout << "\n\nyou have finished inputting.\n have imputed " << size << " numbers. \nthe inputed numbers follows:\n"; for(int i=0; < size; i++){ cout << a[i]; if (i == size -1){ cout << "\n\n"; } else { cout << ", "; } } cout << "\n\n"; } system("pause"); }
the instructor wants comments on every line why there many.
if me wonderful.
delete[] a; //remove old array.
this deletes a
array declared in outer scope of main()
function, top.
next line:
float *a = new float [max];
this creates new variable named a
in inner scope. going forward, think happening original a
, declared @ beginning of main()
being done other a
. original a
"hidden", and, such, when scope ends, new array allocated leaked, , original a
array pointing unallocated memory.
hillarity ensues.
"the more overthink plumbing, easier stop drain" - scotty, star trek iii.
after allocated new b
array, , copied contents of a
it, needed was:
a=b;
you don't need allocate a
array, , copy b
, delete b
. accomplishes absolutely nothing, , doing inadvertently ended making evil mistake...
Comments
Post a Comment