0

I'm practicing operator overloading, and my goal is to enumerate all the values of a vector class I have written myself.

In doing this I came across a segfault (no biggie) and started to pare back my code to find where it originated. After some difficulty, I've come to a point where I don't understand what's going wrong.

While trying to run a for loop to iterate over the data in a vector object, I found that I get a segfault if I use a variable s which is set to 10. If I use the integer literal 10, it works.

This makes very little sense to me, but then again I'm working with unfamiliar concepts. Any help is appreciated!

Here's an MCVE:

Compile using g++ Q1.cpp vector.h -o Q1

Demo class (Q1.cpp):

#include <iostream>
#include "vector.h"

#define INFO(x) std::cout << "[INFO]: " << x << std::endl;

int main(void) {
    // 1- Test the default constructor
    INFO(" ---------- Vector 1 ----------");
    vector v1;
    INFO(v1);

   return 0;
}

Vector class (vector.h):

#include <iostream>
#include <string>

class vector {
public:
    float size;
    float* data;

    vector() : vector(0) {}

    vector(int s){
        size = s;
        data = new float[size]();
    }
};

std::ostream& operator<<(std::ostream& stream, const vector& obj){
    stream << "vector: size(" << obj.size << ")" << "\n";

    int s = 10;

    for(int i = 0; i < s; ++i){  // problem occurs here, replace s with '10' and it works.
        stream << i;
        //stream << "data[" << i << "] = " << obj.data[i]; 
    } 
}
Howard P
  • 258
  • 3
  • 19

1 Answers1

2

Your overloaded function needs to return stream.

Also, don't use size_t as a class member name. It's utterly confusing.

You should also delete the data array when the vector is deleted. It now leaks.

Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108
  • Thanks, will do, I tend to refactor after I know my code works. Is there an intuitive reason that not returning stream would cause this error? My IDE didn't even pick up this error. – Howard P Jun 22 '19 at 20:27
  • 2
    @HowardP See this: https://stackoverflow.com/questions/1610030/why-does-flowing-off-the-end-of-a-non-void-function-without-returning-a-value-no/1610454#1610454 – πάντα ῥεῖ Jun 22 '19 at 20:28
  • 2
    @HowardP The link πάντα ῥεῖ shared explains it. Your IDE may have options to turn on more warnings which would help in these cases. – Ted Lyngmo Jun 22 '19 at 20:32