Segmentation fault with vector in C++ - c++

I am new to C++ and I have a question (sorry if it is something too basic but I want to know). So I have this code which is supposed to multiply every element of a vector with a number:
#include<iostream>
#include "IntCell.h"
#include<vector>
using namespace std;
vector<float> MatMult(int a, vector<float> & b)
{
vector<float> c;
int i;
for(i=0;i<=b.size();i++){
c[i]=b[i]*a;
}
return c;
}
int main()
{int a=3;
vector<float> b{1,2,3,4,5};
vector<float> c = MatMult(a,b);
cout<<c[2];
}
It compiles fine, but I get Segmentation fault: 11. What is wrong about it?
Thank you!

If you have a reasonably current compiler this is simpler. Take the vector by value and multiply using a range-based for loop to avoid out-of-range bugs.
vector<float> MatMult(int a, vector<float> b)
{
for (float& value : b) {
value *= a;
}
return b;
}
This can be made more generic as a template function. Note the code below almost certainly can be improved.
template <typename T>
vector<T> MatMult(int a, vector<T> b)
{
for (auto& value : b) {
value *= a;
}
return b;
}

vector<float> c; creates an empty vector. You then uses it in c[i]=b[i]*a; which is undefined behavior as c[anything] does not exist.
You need to make c the same size as b if you want to use c[i]=b[i]*a;. That would look like:
vector<float> MatMult(int a, vector<float> & b)
{
vector<float> c(b.size());
for(int i = 0; i < b.size(); i++){
// ^ use < here since b[b.size()] is out of bounds
c[i]=b[i]*a;
}
return c;
}

You can't just do c[i] since there's no such index yet. You'd better write c.push_back(b[i] * a) or preallocate memory with c.reserve(b.size()).
What's more, b.size() returns the number of elements in a vector, not the biggest index, so you should use i < b.size() instead of i <= b.size().

In addition to the other answers given, one way to discover right away if you are accessing vectors out of bounds is to first develop using vector::at() and not use [].
vector<float> MatMult(int a, vector<float> & b)
{
vector<float> c;
int i;
for(i=0;i<=b.size();i++){
c.at(i) = b.at(i) * a;
}
return c;
Instead of a segmentation fault, you would have been given an out_of_range exception, thus giving you much more information on what the issue is. Once you rid yourself of all of the out_of_range errors, you can then switch to using [].
Live Example using vector::at

Related

Facing error in c++ arrays and pointers

I am writing this c++ code to multiply two 2d matrices and return the resultant 2d matrix.
The error is cannot convert ll (*)[2] to ll**
ll** multiply(ll a[2][2],ll b[2][2])
{
ll ans[2][2];
ans[0][0]=((a[0][0]*b[0][0])%mod+(a[0][1]*b[1][0])%mod)%mod;
ans[0][1]=((a[0][0]*b[0][1])%mod+(a[0][1]*b[1][1])%mod)%mod;
ans[1][0]=((a[1][0]*b[0][0])%mod+(a[1][1]*b[1][0])%mod)%mod;
ans[1][1]=((a[1][0]*b[0][1])%mod+(a[1][1]*b[1][1])%mod)%mod;
return ans;
}
You have a fallen into a trap that seems to get a lot of newcomers to the language.
Passing 2D arrays to a function and returning 2D arrays to a function leads to error prone code. Using a strut/class removes those errors.
In your case, since the size of the arrays is fixed, you can easily use a struct
struct MyMatrix
{
ll data[2][2];
};
then, update multiply to use MyMatrix instead of 2D arrays.
MyMatrix multiply(MyMatrix const& a, MyMatrix const& b)
{
MyMatrix ans;
...
return ans;
}
You can change the function to an overloaded operator too.
MyMatrix operator*(MyMatrix const& a, MyMatrix const& b)
{
MyMatrix ans;
...
return ans;
}
and simplify usage to:
MyMatrix a{ fill in the data for a};
MyMatrix b{ fill in the data for b};
MyMatrix c = a*b;

Is there a way to auto-promote `vector<int>` to `vector<double>` during function invocation using C++11?

If I define a function which takes a double, I can generally call it with an int and get correct behavior.
double square(double d) {
return d * d;
}
square(1); // valid call
However, if I have a function that takes vector<double>, it is not valid to call it with vector<int>
double sum(const vector<double>& d) {
double s = 0;
for (int i = 0; i < d.size(); i++)
s += d[i];
return s;
}
vector<int> f(1,5);
sum(f); // Compiler error
One solution to this would be to use templates:
template<typename T>
double tsum(const vector<T>& d) {
double s = 0;
for (int i = 0; i < d.size(); i++)
s += d[i];
return s;
}
vector<int> f(1,5);
tsum<int>(f); // Valid
However, in this case, we have to specify the type as part of the function, which is a little clunky, especially if I want to define a dot product function which can do the dot products of arbitrary combinations of numeric types, such vector<int> and vector<double> and vector<float>, because now every time this function is called, the caller has to explicitly specify which vector is which particular numeric type.
Is there some way to define a function, either using traditional or new c++, such that calls like
sum(f) are valid and behave as expected?
You don't actually have to specify it (the compiler will "find it" through what's known as template argument deduction as #FredOverflow has mentioned in the comments):
#include <iostream>
#include <vector>
template<typename T>
T tsum(std::vector<T> const& d)
{
T s = 0;
for(auto x : d) { s += x; }
return s;
}
int main()
{
std::vector<int> f(1,5);
tsum(f);
std::vector<double> v(2, 6);
tsum(v);
return 0;
}
Live example
It should be noted that the standard library contains a function to do this already though: accumulate

Alterative array representation

I'm facing a problem in C++ for which I currently don't have an elegant solution. I'm receiving data in the following format:
typedef struct {
int x;
int y;
int z;
}Data3D;
vector<Data3D> v; // the way data is received (can be modified)
But the functions that do the computations receive parameters like this:
Compute(int *x, int *y, int *z, unsigned nPoints)
{...}
Is there a way to modify the way data is received Data3D so that the memory representation would change from:
XYZXYZXYZ
to
XXXYYYZZZ
What I'm looking for is some way of populating a data structure in a similar way we populate an array but that has the representation above (XXXYYYZZZ). Any custom data structures are welcome.
So I want to write something like (in the above example):
v[0].x = 1
v[0].y = 2
v[0].y = 0
v[1].x = 6
v[1].y = 7
v[1].z = 5
and to have the memory representation below
1,6...2,7....0,5
1,6 is the beginning of the x array
2,7 is the beginning of the y array
0,5 is the beginning of the z array
I know that this can be solved by using a temporary array but I'm interested to know if there are other methods for doing this.
Thanks,
Iulian
LATER EDIT:
Since there are some solutions that change only the declaration of Compute function without changing its code - this should be taken into account also. See the answers related to the solution that involves using an iterator.
Iterator-based solution
An elegant solution would be to make Compute() accept iterators instead of pointers. The iterators you provide will have an adequate ++ operator (see boost::iterator for an easy way to build them)
Compute(MyIterator x, MyIterator y, MyIterator z);
There are normally very few changes to make to the function body, since *x, x[i] or ++x will be handled by MyIterator to point to the right memory location.
Quick'n Dirty solution
A less elegant but more straightforward solution is to hold your Data in the following struct
typedef struct {
std::vector<int> x;
std::vector<int> y;
std::vector<int> z;
}DataArray3D;
When receiving the data fill your struct like
void Receive(const Data3D& data, DataArray3D& array)
{
array.x.push_back(data.x);
array.y.push_back(data.y);
array.z.push_back(data.z);
}
and call Compute like this (Compute itself is unchanged)
Compute(&array.x[0], &array.y[0], &array.z[0]);
You could of course change your computer function.
I assume that all operation done on your int* in compute are dereference and increment operation.
I did not test it but you could pass in a structure like this
struct IntIterator
{
int* m_currentPos;
IntIterator(int* startPos):m_currentPos(startPos){};
IntIterator& operator++()
{
m_currentPos += 3;
return *this;
}
IntIterator& operator++(int)
{
m_currentPos += 3;
return *this;
}
int operator*()
{
return *m_currentPos;
}
int& operator[](const int index)
{
return m_currentPos[index*3];
}
};
And initialize it with this
std::vector<Data3D> v;
IntIterator it(&v[0].x);
Now all you need to do is change the type of your compute function arguments and it should do it. If of course some pointer arithmetics are used than it is getting more complex.
Reasonably elegant would be (not compiled/tested):
struct TempReprPoints
{
TempReprPoints(size_t size)
{
x.reserve(size); y.reserve(size); z.reserve(size);
}
TempReprPoints(const vector<Data3D> &v)
{
x.reserve(v.size()); y.reserve(v.size()); z.reserve(v.size());
for (size_t i = 0; i < v.size(); ++i ) push_back(v[i]);
}
void push_back(const Data3D& data)
{
x.push_back(data.x); y.push_back(data.y); z.push_back(data.z);
}
int* getX() { return &x[0]; }
int* getY() { return &y[0]; }
int* getZ() { return &z[0]; }
size_t size() { return x.size(); }
std::vector<int> x;
std::vector<int> y;
std::vector<int> z;
};
So you can fill it with a loop or even try to make the std::back_inserter work with it.
In order to get the syntax you want, you could use something like this.
struct Foo {
vector<int> x;
vector<int> y;
vector<int> z;
struct FooAccessor {
FooAccessor(Foo & f, int i) : x(f.x[i]), y(f.y[i]), z(f.z[i]) {}
int &x, &y, &z;
};
FooAccessor operator[](int i) {
return FooAccessor(*this, i);
}
};
int main() {
Foo f;
f.x.resize(10);
f.y.resize(10);
f.z.resize(10);
f[0].x = 1;
f[1].y = 2;
f[2].z = 3;
for (size_t p = 0; p < 10; ++p) {
cout << f.x[p] << "," << f.y[p] << "," << f.z[p] << endl;
}
}
I'd consider this an ugly solution - changing the way you access your data would likely be "better".

How to return a 2 dimensional vector?

I have a function that creates a 2D vector
void generate(int n)
{
vector< vector<int> > V (n, vector<int>(1 << n , 0 ));
.......
}//n is used to determine the size of vector
Now, I need to return the created vector to use it in another function .If I did
return V ;
it will be wrong because V is a local variable but I can't define V outside the function because this functions defines the size of V . What should I do ?
You can return V with no issues - it will return a copy of the local variable. Issues only arise when you return a reference or pointer to a variable with local scope; when the function ends, the local variable falls out of scope and is destroyed and the reference/pointer is no longer valid.
Alternatively, you can accept a reference to a vector as your argument, write to it and return void:
void generate(int n, std::vector< std::vector<int> >& vec) {
vec.resize(n, std::vector<int>(1 << n, 0));
}
int main() {
std::vector< std::vector<int> > v;
generate(10, v);
}
This is faster than returning a copy of the local member, which can be expensive for large objects such as multi-dimensional vectors.
vector<vector<int> > generate(int n)
{
vector<vector<int> > v(n, vector<int>(1 << n, 0));
//...
return v;
}
The return value is a copy of the local variable v so there is no problem at all.
If you're concerned about copying the vector, maybe you could do something like this:
void generate(int n, vector<vector<int> >& v)
{
v.clear(); //not necessary if you're sure it's empty
v.resize(n, vector<int>(1 << n, 0));
//...
}
if the vector is small, just return it by value, it will be copied.
if the vector is large, the caller can pass the dest vector by reference.
As alternative to other answers you can return pointer to heap allocated vector. For securing from memory leaks you can use "move constructor" idiom.
typedef auto_ptr<vector<vector<int> > > vector_ptr;
vector_ptr generate(int n)
{
vector_ptr V(new vector<vector<int> >(n, vector<int>(1 << n , 0 )));
return V;
}
// ...
vector_ptr V(generate(some_number));
This idiom can be used for any "heavy" object. If you whant to prolonge lifetime of returned object you can assign it to shared_ptr (as example boost::shared_ptr). But I think it is better return copy whenever it is possible, for minimizing complexity of your code.
Just like we do for other,we can do that here also.See my code for better explanation I have given my code for matrix multiplication in which i have made a function for it and returned a matrix as a 2D vector.
`
#include <bits/stdc++.h>
using namespace std;
vector<vector<int>> mul(vector<vector<int>> a,vector<vector<int>> b)
{
int n=a.size();
int k=a[0].size();
int m=b[0].size();
vector<vector<int>> c(n,vector<int> (m,0));
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
c[i][j]=0;
for(int m=0;m<k;m++)
{
c[i][j]+=(a[i][m]*b[m][j]);
}
}
}
return c;
}
int main() {
vector<vector<int>> l={{1,2}};
vector<vector<int>> r={{1,2,3},{4,5,6}};
vector<vector<int>> m;
m=mul(l,r);
for(int i=0;i<m.size();i++)
{
for(int j=0;j<m[i].size();j++)
{
cout<<m[i][j]<<" ";
}
cout<<endl;
}
return 0;
}
`

dynamical two dimension array according to input

I need to get an input N from the user and generate a N*N matrix. How can I declare the matrix? Generally, the size of the array and matrix should be fixed at the declaration, right?
What about vector<vector<int>> ? I never use this before so I need suggestion from veteran.
A vector<vector<int>> (or vector<vector<int> >, for older compilers) can work well, but it's not necessarily the most efficient way to do things1. Another that can work quite nicely is a wrapper around a single vector, that keeps track of the "shape" of the matrix being represented, and provides a function or overloaded operator to access the data:
template <class T>
class matrix {
int columns_;
std::vector<T> data;
public:
matrix(int columns, int rows) : columns_(columns), data(columns*rows) {}
T &operator()(int column, int row) { return data[row*columns_+column]; }
};
Note that the C++ standard only allows operator[] to take a single operand, so you can't use it for this job, at least directly. In the example above, I've (obviously enough) used operator() instead, so subscripts look more like Fortran or BASIC than you're accustomed to in C++. If you're really set on using [] notation, you can do it anyway, though it's mildly tricky (you overload it in the matrix class to return a proxy, then have the proxy class also overload operator[] to return (a reference to) the correct element -- it's mildly ugly internally, but works perfectly well anyway).
Here's an example of how to implement the version using multiple overloads of operator[]. I wrote this (quite a while) before most compilers included std::vector, so it statically allocates an array instead of using a vector. It's also for the 3D case (so there are two levels of proxies involved), but with a bit of luck, the basic idea comes through anyway:
template<class T, int size>
class matrix3 {
T data[size][size][size];
friend class proxy;
friend class proxy2;
class proxy {
matrix3 &m_;
int index1_, index2_;
public:
proxy(matrix3 &m, int i1, int i2)
: m_(m), index1_(i1), index2_(i2)
{}
T &operator[](int index3) {
return m_.data[index1_][index2_][index3];
}
};
class proxy2 {
matrix3 &m_;
int index_;
public:
proxy2(matrix3 &m, int d) : m_(m), index_(d) { }
proxy operator[](int index2) {
return proxy(m_, index_, index2);
}
};
public:
proxy2 operator[](int index) {
return proxy2(*this, index);
}
};
Using this, you can address the matrix with the normal C++ syntax, such as:
matrix3<double, size> m;
for (int x=0; x<size; x++)
for (int y = 0; y<size; y++)
for (int z = 0; z<size; z++)
m[x][y][z] = x*100 + y * 10 + z;
An std::vector is normally implemented as a pointer to some dynamically allocated data, so something like a vector<vector<vector<int>>> will dereference two levels of pointers to get to each piece of data. This means more memory references, which tend to be fairly slow on most modern processors. Since each vector contains separately allocated data, it also leads to poor cache locality as a rule. It can also waste some space, since each vector stores both its allocated size and the size in use.
Boost implements matrices (supporting mathematical operations) in its uBLAS library, and provides usage syntax like the following.
#include <boost/numeric/ublas/matrix.hpp>
int main(int argc, char* argv[])
{
unsigned int N = atoi(argv[1]);
boost::matrix<int> myMatrix(N, N);
for (unsigned i = 0; i < myMatrix.size1 (); ++i)
for (unsigned j = 0; j < myMatrix.size2 (); ++j)
myMatrix(i, j) = 3 * i + j;
return 0;
}
Sample Code:
template<class T>
class Array2D
{
public:
Array2D(int a, int b)
{
num1 = (T**)new int [a*sizeof(int*)];
for(int i = 0; i < a; i++)
num1[i] = new int [b*sizeof(int)];
for (int i = 0; i < a; i++) {
for (int j = 0; j < b; j++) {
num1[i][j] = i*j;
}
}
}
class Array1D
{
public:
Array1D(int* a):temp(a) {}
T& operator[](int a)
{
return temp[a];
}
T* temp;
};
T** num1;
Array1D operator[] (int a)
{
return Array1D(num1[a]);
}
};
int _tmain(int argc, _TCHAR* argv[])
{
Array2D<int> arr(20, 30);
std::cout << arr[2][3];
getchar();
return 0;
}
enter code here