Vector subscript but not array out of range

I am not sure why having a vector instead of an array is a problem here. I've narrowed down my issue to the following. I can use cout to print out each element in the vector but I can't fill up the memory vector. If I create an array titled memory instead, I can get no errors trying to set memory[pc + i] = prog[i];

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
 
typedef uint32_t i32;

int main()
{
std::vector<i32> memory;
memory.reseve(10000000);
//i32 memory[100000];
std::vector<uint32_t> prog  { 3, 4, 0x40000001, 0x40000000 };

		for (int i = 0; i < prog.size(); i++) {
		//cout << i << ": "<< prog[i]<<endl;
			memory[pc + i] = prog[i];
	}

return 0;
}
https://ideone.com/XggDAS

Works fine there.
I get errors with the snippet posted.

Line 7: reserve is misspelled.

Line 13: pc is undefined.
And don't forget that reserve doesn't alter the size of the vector and since your "memory" vector is empty trying to access the vector with the operator[] will produce Undefined Behavior.


Works fine there.

Just because it appears to "work fine" doesn't actually mean it is correct.
Last edited on
Topic archived. No new replies allowed.