out of range at memory location error

at line 59-60, my program always stops working says their is an error saying I am out of the range of memory location. What does this mean and why can't I output a vector that i passed in my function. I have the right parameters don't I?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
  #include "stdafx.h"
#include <iostream>
#include <vector>
using namespace std;

void readarray(int array1[100], int& counter);
void printarray(int array1[100], int counter);
void copyarray(int array1[100], vector<int>&v1, int counter);
void printvector(vector<int>v1);

int main()
{
	int myarray[100], b;
	vector<int>myvector;
	readarray(myarray, b);
	printarray(myarray, b);
	copyarray(myarray, myvector, b);
	printvector(myvector);
	system("pause");
    return 0;
}

void readarray(int array1[100], int& counter)
{
	int num;
	for (int x = 0; x < 10; x++)
	{
		cout << "Enter element: ";
		cin >> num;
		counter++;
		array1[x] = num;
	}
}

void printarray(int array1[100], int counter)
{
	for (int x = 0; x < counter; x++)
	{
		cout << array1[x]<<" ";
	}
	cout << endl;
}

void copyarray(int array1[100], vector<int>&v1, int counter) 
{
	for (int x = 0; x < counter; x++)
	{
		v1.push_back(array1[x]);
	}
}

void printvector(vector<int>v1)
{
	int biggest = 0;
	for (unsigned int x = 0; x < v1.size(); x++)
	{
		if (v1.at(x) > biggest)
		{
			cout << v1.at(x);
			biggest = v1.at(x);
		}
	}
	cout << biggest << endl;
}
Last edited on
closed account (E0p9LyTq)
Where are you initializing your b variable?

No where, so you are using whatever garbage value it contains.
but how does that apply to my printvector() function?
it solved my problem, but i'd like you to explain this. Why did i get the error at lines 59-60? shouldn't it tell me that the minute I try to increase the value of B?
closed account (E0p9LyTq)
There is no one answer to undefined behavior. Using an undefined variable as the limiter in a for loop is undefined behavior and can show up anywhere in your program. It just happened to cause problems with what seems to be an unrelated function.

Do you know what the actual number of elements were contained in your vector? No, you don't. You define an array to be 100 elements, and then likely proceed to read more than 100 elements into your vector. b in main() becomes counter in your 3 array functions.

readarray() increments a garbage value and that garbage value gets thrown into printarray() and copyarray().

GIGO, garbage in, garbage out.

It looks like you are using Visual Studio. VS in debug mode initializes variables to zero, something it doesn't do in release mode. Lots of bugs can creep in when changing that configuration.
Last edited on
Topic archived. No new replies allowed.