Using a variable in a for loop, causing segfault [duplicate] - c++

This question already has an answer here:
Why does this simple C++ code segfault? [closed]
(1 answer)
Closed 3 years ago.
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];
}
}

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.

Related

C++ Segmentation fault core dumped for simple vector operation [duplicate]

This question already has answers here:
Assigning values to 2D Vector by using indices
(3 answers)
Closed 1 year ago.
I have the following code c++ code
#include <vector>
#include <iostream>
using namespace std;
#define for_loop(upper_bound) for (int i=0;i<upper_bound; ++i)
// #define SHOW_VECTOR(vec_in) for(int j=0;j<vec_in.size();j++){ cout << vec_in[j] << " " << endl;};
int main(){
int dim_1=10;
int dim_2=3;
int outer_i;
// vector variable declared here to have 10 values
vector<vector<int>>vec_var(dim_1);
for_loop(dim_1){
outer_i = i;
for_loop(dim_2){
cout << outer_i << " " << i << endl;
vec_var[outer_i][i]=103;
}
}
return 0;
}
When I try and run it i get the following error:
Segmentation fault (core dumped)
You need to size both your outer and inner vectors
vector<vector<int>> vec_var(dim_1, vector<int>(dim_2));
// ^ inner vector default size
Otherwise as written, you have an outer vector if size dim_1 but all of the inner vectors are empty.
As an aside, since I notice you then filling the vector with constant values, you can do all that in one step too
vector<vector<int>> vec_var(dim_1, vector<int>(dim_2, 103));
// ^ default of inner vector elements
Subscripting a std::vector does not cause that element position to be created. You need to resize, push_back, or otherwise add elements to the vectors! You indexed things that are out of range.
The outer vector is defined with a constructor argument that sizes it to dim_1, but each of those inner vectors does not have any elements. So follow it up with:
for (auto& inner : vec_var) inner.resize(dim_2);
Also, suggest using the built-in range-based for loop instead of your macro. That you need to manually save the index in your outer loop shows that your macro is not really the most convenient!
int main()
{
constexpr int dim_1=10;
constexpr int dim_2=3;
vector<vector<int>>vec_var(dim_1);
for (auto& outer : vec_var) {
outer.resize (dim_2);
for (auto& inner : outer) {
inner=103;
}
}
return 0;
}
But really, this is not normal. You probably should be using push_back to add the values, rather than resizing it and then subscripting each element in order.
You only set the dimension of the outer vector. You need to set the dimension of the inner vectors as well.
#include <vector>
#include <iostream>
using namespace std;
#define for_loop(upper_bound) for (int i=0;i<upper_bound; ++i)
// #define SHOW_VECTOR(vec_in) for(int j=0;j<vec_in.size();j++){ cout <<
vec_in[j] << " " << endl;};
int main(){
int dim_1=10;
int dim_2=3;
int outer_i;
// vector variable declared here to have 10 values
vector<vector<int>>vec_var(dim_1);
for_loop(dim_1){
outer_i = i;
vec_var[outer_i].resize(dim_2); // ADD THIS
for_loop(dim_2){
cout << outer_i << " " << i << endl;
vec_var[outer_i][i]=103;
}
}
return 0;
}

How to use std::copy? not working on OSXSierra/CLION/C++11. [duplicate]

This question already has answers here:
std::vector::resize() vs. std::vector::reserve()
(5 answers)
Closed 6 years ago.
I was unable to make std::copy works. I tried several codes in internet, but I was unable to make it work. I need to use copy, first, to understand why is not working, second, to use it in a constructor of a class(I can't declare a new variable in the constructor).
I have this code:
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> myVector;
vector<int> vectorCopy;
for (int i = 0; i < 10; i++) {
myVector.push_back(i);
}
cout << vectorCopy.size() << endl; //0
vectorCopy.reserve(myVector.size());
cout << vectorCopy.size() << endl; //PROBLEM: again 0
copy(myVector.begin(), myVector.end(), vectorCopy.begin());
cout << vectorCopy.size() << endl; //PROBLEM 2: again 0
for (int j = 0; j < vectorCopy.size(); j++) {
cout << vectorCopy[j] << endl;//never execute;
}
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
return 0;
}
Any ideas? I'm using CLION on MacOS Sierra and C++11.
Thanks!!
You need to pass an output iterator as the third parameter to std::copy(). Usually you'll use something like a std::back_inserter.

Memory corruption with std::initializer_list [duplicate]

This question already has answers here:
C++11 initializer list fails - but only on lists of length 2
(2 answers)
Closed 8 years ago.
I have memory corruption in this code:
#include <string>
#include <iostream>
#include <vector>
#include <initializer_list>
int main() {
std::vector<std::initializer_list<std::string>> lists = {
{
{"text1"},
{"text2"},
{"text3"}
},
{
{"text4"},
{"text5"}
}
};
int i = 0;
std::cout << "lists.size() = " << lists.size() << std::endl;
for ( auto& list: lists ) {
std::cout << "lists[" << i << "].size() = " << lists[i].size() << std::endl;
int j = 0;
for ( auto& string: list ) {
std::cout << "lists[" << i << "][" << j << "] = "<< string << std::endl;
j++;
}
i++;
}
}
Sample output:
lists.size() = 2
lists[0].size() = 3
lists[0][0] = text10�j ����text2H�j ����text3`�j ����text4����text5��������q
The problem is in std::initializer_list. Changing std::initializer_list to std::vector solves the problem.
The question is why memory corruption takes place with std::initializer_list?
Because of std::string objects were destroyed before this line:
int i = 0;
If std::string has debug output in their destructors and ctors. You will be see something like:
std::string::string 5 times,
std::string::~string 5 times
and after that
lists.size() = 2
Because of initializre_list not contain copy of std::string objects, they (temporary std::string objects0 just created and destroyed before ';'
It is for example like take reference to std::string object
in such expression:
std::cout << std::string("17");
But if you replace std::string with "const char *" in your example all should works, I suppose.
Storage for initializer list is destroyed after usage, which is before line:
int i = 0;
Its details are implementation spesific, but it generally creates a dynamic array at construction and this dynamic array is destroyed at destruction.
You can find more detail at cppreference page

c++ overload pointer ostream

I am a learning c++ and have a class project due in 5 days. I've spent 4 hours researching how to do this however I have not come up with an answer yet. Save me stack!
Problem. I have a pointer to a class which holds a dynamic array. I need to take that array and save it to a file to retrieve later. Here are my 2 headers and the implementation. I am not writing the code to "save to file" yet as that will be easy once I get around this issue. My problem is it keeps printing the address of the pointer and not the data within.
vehReg.h
class vehReg {
public:
/* STUFF */
};
}
#endif
vehData.h
#include "vehReg.h"
using namespace std;
class vehData {
public:
//CONSTRUCTORS
vehData();
//DECONSTRUCTOR
~vehData();
//METHODS
friend ostream &operator<<( ostream &output, const vehData &v);
private:
typedef unsigned long longType;
typedef std::size_t sizeType;
sizeType used,capacity;
vehReg *data;
};
}
#endif
vehData.cpp
//CONSTRUCTOR
vehData::vehData(){
capacity = 5;
used = 0;
data = new vehReg[capacity];
}
//DECONSTRUCTOR
vehData::~vehData(){
delete []data;
}
/* TRYING TO ACCOMPLISH THIS WITH AN OSTREAM OVERLOAD */
void vehData::saveDataSloppy(){
ofstream myFile;
myFile.open ("database.db");
for(int i=0;i<used;i++){
myFile << data[i].getOwnerName() << "|";
myFile << data[i].getVehicleLicense() << "|";
myFile << data[i].getVehicleMake() << "|";
myFile << data[i].getVehicleModel() << "|";
myFile << data[i].getVehicleYear() << "\n";
}
myFile.close();
}
void vehData::saveData(){
cout << data;
}
ostream &operator<<(ostream &stream, const vehData &v){
stream << v.data;
}
}
v.data is a pointer, so it prints a pointer. How do you want it to
print whatever the pointer points to. With the exception of character
pointers, the << always prints what you give it (formatted in some
way). If you don't want it to print a pointer, give is something else.
Suppose it did dereference the pointer. What should it print: one
vehReg? 20? A pointer has no information concerning the size. If
you'd used std::vector<vehReg> (a much better choice), it would know
the size, but there's still no overload on std::vector, since the
system still doesn't know how you want it formatted (comma separated?
each on a new line?). And you've not told it how to print a vehReg
either.
You apparently understand the idea of how to overload <<. The first
thing you'll have to do is provide an overload for vehReg as well.
And both overloads must be defined in terms of existing overloads:
there's not one for std::vector, and the one for pointer doesn't do
what you want (and couldn't), so you'll have to loop in your << for
vehData and output each element, with whatever separators you decide
on. (If it's each element on its own line, then you can use std::copy
and an ostream_iterator for the loop, but this may be a bit in advance
of what you've learnt so far.) And forward to the << for vehReg for
each vehReg.
v.data is a pointer so it's a memory address.
*v.data is what the pointer is pointing to (which in this case is an integer).
For example,
#include <iostream>
using namespace std;
void main () {
int *ptr;
int var = 5;
ptr = &var;
cout << ptr << endl;
cout << *ptr << endl;
system("pause");
}
First line will print out something like: 0043F930
Second line will print out: 5
This should print out the elements held in the data array.
void vehData::showStructure() const {
for (int i = 0; i < capacity: i++) {
cout << data[i];
}
cout << endl;
}

C++: Why is my vector of structs acting as one struct?

I'm working my way through Accelerated C++ and have decided to mess around with the one of structs that were defined in there. While doing so, I've come across a problem: creating a vector of these structs and modifying the elements in each one seems to modify the elements in all of them.
I realize that this probably means I've initialized all the structs in the vector to a struct at a single memory address, but I used the .push_back() method to insert "dummy" structs in to the vector. I was under the impression that .push_back() pushes a copy of its argument, effectively creating a new struct.
Here is the header for the struct:
#ifndef _STUDENT_INFO__CHAPTER_9_H
#define _STUDENT_INFO__CHAPTER_9_H
#include <string>
#include <iostream>
#include <vector>
class Student_info9{
public:
Student_info9(){homework = new std::vector<double>;};
Student_info9(std::istream& is);
std::string getName() const {return name;};
double getMidterm() const {return midterm;};
double getFinal() const {return final;};
char getPassFail() const {return passFail;};
std::vector<double> *getHw(){return homework;};
void setName(std::string n) {name = n;};
void setMidterm(double m) {midterm = m;};
void setFinal(double f) {final = f;};
private:
std::string name;
double midterm;
double final;
char passFail;
std::vector<double> *homework;
};
#endif /* _STUDENT_INFO__CHAPTER_9_H */
And here is the code that i'm fooling around with (excuse the excessive print statements... the result of some time trying to debug :) ):
vector<Student_info9> did9, didnt9;
bool did_all_hw9(Student_info9& s)
{
vector<double>::const_iterator beginCpy = s.getHw()->begin();
vector<double>::const_iterator endCpy = s.getHw()->end();
return(find(beginCpy, endCpy, 0) == s.getHw()->end());
}
void fill_did_and_didnt9(vector<Student_info9> allRecords)
{
vector<Student_info9>::iterator firstDidnt = partition(allRecords.begin(), allRecords.end(), did_all_hw9);
vector<Student_info9> didcpy(allRecords.begin(), firstDidnt);
did9 = didcpy;
vector<Student_info9> didntcpy(firstDidnt, allRecords.end());
didnt9 = didntcpy;
}
int main(int argc, char** argv) {
vector<Student_info9> students;
Student_info9 record;
for(int i = 0; i < 5; i++)
{
students.push_back(record);
}
for(int i = 0; i < students.size(); i++)
{
students[i].setMidterm(85);
students[i].setFinal(90);
students[i].getHw()->push_back(90);
std::cout << "student[" << i << "]'s homework vector size is " << students[i].getHw()->size() << std::endl;
students[i].getHw()->push_back(80);
std::cout << "student[" << i << "]'s homework vector size is " << students[i].getHw()->size() << std::endl;
students[i].getHw()->push_back(70);
std::cout << "student[" << i << "]'s homework vector size is " << students[i].getHw()->size() << std::endl;
std::cout << "Just pushed back students[" << i << "]'s homework grades" << std::endl;
if(i == 3)
students[i].getHw()->push_back(0);
}
std::cout << "student[3]'s homework vector size is " << students[3].getHw()->size() << std::endl;
for(vector<double>::const_iterator it = students[3].getHw()->begin(); it != students[3].getHw()->end(); it++)
std::cout << *it << " ";
std::cout << std::endl;
std::cout << "students[3] has " << ( ( find(students[3].getHw()->begin(),students[3].getHw()->end(), 0) != students[3].getHw()->end()) ? "atleast one " : "no " )
<< "homework with a grade of 0" << std::endl;
fill_did_and_didnt9(students);
std::cout << "did9's size is: " << did9.size() << std::endl;
std::cout << "didnt9's size is: " << didnt9.size() << std::endl;
}
As you can see by the print statements, it seems that the homework grades are being added only to one Student_info9 object, copies of which seem to be populating the entire vector. I was under the impression that if you were to use consecutive copies of .push_back() on a single object, it would create copies of that object, each with different memory addresses.
I'm not sure if that's the source of the problem, but hopefully someone could point me in the right direction.
Thanks.
When you push a StudentInfo onto the vector, it is indeed copied, so that's not the problem. The problem is the vector containing the homework grades. Since you only store a pointer to that vector in StudentInfo, only the pointer, not the vector, is copied when you copy a StudentInfo. In other words you have many different StudentInfos that all have a pointer to the same homework vector.
To fix this you should define a copy constructor which takes care of copying the homework vector.
Have you learned about the copy constructor yet? If so, think about what is happening with vector<Student_info9> students on push_back().
Specifically, what happens with this pointer.
std::vector<double> *homework;
The line Student_info9 record; constructs a Student_info9 using the first constructor. This first constructor creates a vector and stores a pointer to it as a member variable. You then proceed to add a copy of this Student_info9 to a vector 5 times. Each copy has a pointer to the same vector.
Your StudentInfo9 class contanis a pointer to a std::vector<double>, which means in the default copy constructor (which will be called when you add a StudentInfo9 object to your vector), the pointer itself is copied. That means all of your StudentInfo9 objects have the same homework vector.
Does that make sense? Please refer to http://pages.cs.wisc.edu/~hasti/cs368/CppTutorial/NOTES/CLASSES-PTRS.html for a more in depth look at pointers and copy constructors.