I have the following code to print a vector in c++. It works fine for non-empty vectors, but for some reason it gives a segmentation fault when you try to print an empty vector.
#include <iostream>
#include <vector>
using namespace std;
void printVector(const vector<int>& v) {
cout << "{";
for (int i = 0; i < v.size() - 1; i++)
cout << v[i] << ", ";
if(v.size() > 0) cout << v[v.size() - 1];
cout << "}" << endl;
}
int main() {
vector<int> v = vector<int>(0);
printVector(v);
}
For an empty vector v, v.size() = 0 so v.size() – 1 = -1 which is not > 0, therefore the loop will never be entered. The same happens with the if conditional. So the only 2 lines that should be executed are the ones that print “{” and “}n”.
Instead, this code outputs exactly (it doesn’t even print the first “{“):
Segmentation fault (core dumped)
Then I tried to add some more couts in the code, to see where it breaks. The first modification I made is
void printVector(const vector<int>& v) {
cout << "{";
cout << "Check 1" << endl;
for (int i = 0; i < v.size() - 1; i++)
cout << v[i] << ", ";
if(v.size() > 0) cout << v[v.size() - 1];
cout << "}" << endl;
}
Now it outputs:
{Check 1
Segmentation fault (core dumped)
Which is strange, as now the “{” does appear. My next guess was that maybe the .size() function gives an error for empty vectors, so the for loop condition is what is breaking. To test it, I made the following modification:
void printVector(const vector<int>& v) {
cout << "{";
int aux = v.size();
cout << "Check 1" << " " << aux << endl;
for (int i = 0; i < v.size() - 1; i++)
cout << v[i] << ", ";
if(v.size() > 0) cout << v[v.size() - 1];
cout << "}" << endl;
}
Output:
{Check 1 0
Segmentation fault (core dumped)
I concluded that the problem can’t be with the .size() function, which was my last guess at what is going wrong. Then I asked chat gpt and it gave me this code:
void printVector(vector<int>& v) {
cout << "{";
for (int i = 0; i < v.size(); i++) {
cout << v[i];
if (i < v.size() - 1) {
cout << ", ";
}
}
cout << "}" << endl;
}
Which for some reason works! It looks like the exact same code to me. I feel I am going crazy. It is such a simple program and I can’t even get it to work / find the mistake.