0

I am trying to use (learn) the Vectors in C++ and hence I have written this as a simple example. But I getting the error of 'Segmentation fault: core dumped' and I do not where and what the error is. Can someone try to explain me , what it is?

'''

struct Vertex {

    int x,y,z;
};


std::ostream& operator<<(std::ostream& stream, const Vertex& vertex) {

    stream << vertex.x << ", " << vertex.y << vertex.z;
    return stream;
}


int main() {

    std::vector<Vertex> vertices;
    vertices.push_back({1,2,3});

    for(int idx = 0; vertices.size(); idx++)
        std::cout << vertices[idx] << std::endl;
}

'''

Is ther error because of the operator overloading (<<)? This is just a hunch. Because, When i compile it using g++11, it compiles fine, but when I see the output (using the command ./a.out), the segmentation fault error occurs. Therefore, I am confused.

y_1234
  • 61
  • 1
  • 7
  • 4
    Check your for-loops condition. – tkausl Apr 02 '20 at 12:50
  • look at the [range-based for loop](https://en.cppreference.com/w/cpp/language/range-for), it helps a lot to avoid such typos – 463035818_is_not_an_ai Apr 02 '20 at 12:54
  • How to iterate over a std::vector (different ways): https://stackoverflow.com/questions/409348/iteration-over-stdvector-unsigned-vs-signed-index-variable – Jose Apr 02 '20 at 12:54
  • 1
    *When i compile it using g++11, it compiles fine* -- Compiling fine only means there are no syntax errors. It has no bearing on whether the program has logic errors or not, and if you look at your `for` loop carefully, it contains such an error. – PaulMcKenzie Apr 02 '20 at 13:09

2 Answers2

0

Your error is in the condition for the for loop. You wrote vertices.size(). Change that to idx<vertices.size() and you should be fine. While you're at it, you might want to change your overloaded operator to include a separator between y and z as well ;)

RL-S
  • 734
  • 6
  • 21
0

Applied 2 modifications:

  1. Add include
#include <vector>
#include <iostream>
  1. Fix for-loop condition
for(int idx = 0; idx < vertices.size(); idx++)
    std::cout << vertices[idx] << std::endl;

Full code should work fine

#include <vector>
#include <iostream>

struct Vertex {
    int x,y,z;
};

std::ostream& operator<<(std::ostream& stream, const Vertex& vertex) {
    stream << vertex.x << ", " << vertex.y << ", " << vertex.z;
    return stream;
}

int main() {
    std::vector<Vertex> vertices;
    vertices.push_back({1,2,3});

    for(int idx = 0; idx < vertices.size(); idx++)
        std::cout << vertices[idx] << std::endl;
}
Ardiya
  • 677
  • 6
  • 19