runtime error?



This compiles but chokes on execution. What am I doing wrong?

code::blocks w/g++ error message:
Process terminated with status -1073741819

And the message I get from Windows with VC++ is:
Debug Assertion Failed!
Expression:vector subscript out of range

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
#include <iostream>
#include <vector>
using namespace std;

int main()
{
  vector<int> v,w,x;

  for(int i = 0; i < 25; i++)
    v.push_back(i);
  for(int i = 0; i < v.size(); i++)
    cout << v[i] << " ";
  cout << endl;
  for(int i = 25; i < 50; i++)
    w.push_back(i);
  for(int i = 0; i < w.size(); i++)
    cout << w[i] << " ";
  cout << endl;
  for(int i = 0; i < 25; i++) {
    x[i] = v[i] + w[i];
  cout << x[i] << " ";
  cout << endl;

  return 0;
  }
}


Thanks,
b52
In the last loop you're trying to assign values to members of x, even though x does not contain any elements yet.
You need to use push_back there too.

Edit: you should use the debugger in future (to run the program with the debugger in Code::Blocks, click Debug/Start).
When a segmentation fault occurs, it will show you the problematic line.
To add vector bounds checking in Code::Blocks/g++, go to Project/Build options/#defines and add _GLIBCXX_DEBUG (only for Debug build, of course). Then it will show you the callstack. The line at the bottom with main() is what is of interest to you, it shows that the problem occurred in line 20.
Last edited on
Thanks Athar. Finally got it.

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
#include <iostream>
#include <vector>
using namespace std;

int main()
{
  vector<int> v,w,x;

  for(int i = 0; i < 25; i++)
    v.push_back(i);
  for(int i = 0; i < v.size(); i++)
    cout << v[i] << " ";
  cout << endl;
  for(int i = 25; i < 50; i++)
    w.push_back(i);
  for(int i = 0; i < w.size(); i++)
    cout << w[i] << " ";
  cout << endl;
  for(int i = 0; i < 25; i++)
    x.push_back(i);
  for(int i = 0; i < x.size(); i++)
    x[i] = v[i] + w[i];
  for(int i = 0; i < x.size(); i++)
  cout << x[i] << " ";
  cout << endl;

  return 0;

}


Thanks,
b52
If you're just going to overwrite the values in x anyway, you don't need a loop to fill the vector.
Instead, you can use x.resize(25);
This is the exercise I've been working on:

"Create three vector<int> objects and fill the first two as in the previous exercise. Write a for loop that adds each corresponding element in the first two vectors and put the result in the corresponding element of the third vector. Display all three vectors."

I'm not sure I've got it yet but I don't want to go to the next chapter until a fully understand this one.

Thanks again,
b52
What Athar is saying is instead of having a loop to populate x, then another to overwrite everything you put in it, why not just directly do x.push_back(v[i]+w[i]);
I misunderstood. Thanks for the clarification.
Topic archived. No new replies allowed.