Segmentation fault in matrix multiplication C++ - c++

I'm trying to make a function that receives as parameter two matrixes and returns the multiplication of both. But when I try to test it, it returns a segmentation fault, can anyone tell me why? And help me to fix it?
This is my function code:
#include <iostream>
#include <math.h>
#include <fstream>
#include <vector>
using namespace std;
vector<vector<double> > MMultiplication(vector<vector<double> > a, vector<vector<double> > b) {
int a_columns = a[0].size();
int a_rows = a.size();
int b_columns = b[0].size();
int b_rows = b.size();
< vector<vector<double> > result;
result.resize(a_columns);
for (int i = 0; i < m; ++i)
{
//Grow Columns by b_rows
result[i].resize(b_rows);
}
for (int p = 0; p < a_rows; p++) {
for (int q = 0; q < b_columns; q++) {
result[p][q] = 0;
}
}
if (a_columns != b_rows) {
cout << "Error: The number of columns of the first matrix needs to be equal to the number of rows of the second matrix" << endl;
return result;
}
for (int i = 0; i < a_rows; i++) { //i iterate a rows
for (int j = 0; j = b_columns; j++) //j iterates b columns
{
for (int k = 0; k < a_columns; k++) { //k goes back to a and iterates its columns
result[i][j] += a[i][k] * b[k][j]; //sums all multiplications into result[i][j]
}
}
}
return result;
}
And this is the main i'm using to test my function:
int main ()
{
vector < vector < double >>a;
int m = 4, n = 2;
//Grow rows by m
a.resize (m);
for (int i = 0; i < m; ++i)
{
//Grow Columns by n
a[i].resize (n);
}
a[0] =
{
1, 0};
a[1] =
{
1, 1};
a[2] =
{
1, 2};
a[3] =
{
1, 3};
cout << a.size () << endl;
cout << a[0].size () << endl;
vector < vector < double >>b;
int o = 2, p = 4;
b.resize (o);
for (int i = 0; i < o; i++)
{
b[i].resize (p);
}
b[0] =
{
1, 2, 3, 4};
b[1] =
{
1, 3, 5, 7};
vector < vector < double >>result = MMultiplication (a, b);
cout << result.size () << endl;
cout << result[0].size () << endl;
/* for(int k = 0; k < result.size(); k++) {
for(int q = 0; q < result[0].size(); q++)
cout << result[k][q] << endl;
} */
}
Also, it's important to point out that the function, so far, is returning a matrix of zeros if it's impossible to multiply a and b.
Thank you.

Related

Static array and Dynamic array in a function

I have a question as below C++ code.
this is the code(No function) that can successful execute.
#include <iostream>
using namespace std;
int main()
{
int size_3 = 3;
//arr1 is a static array
int arr1[3][3] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };
//arr2 is a dynamic array
int** arr2 = new int* [size_3];
for (int i = 0; i < size_3; i++) {
arr2[i] = new int[size_3];
}
int val = 9;
for (int i = 0; i < size_3; i++) {
for (int j = 0; j < size_3; j++) {
arr2[i][j] = val--;
}
}
cout << "Elements in matrix 1: " << endl;
for (int i = 0; i < size_3; i++) {
for (int j = 0; j < size_3; j++) {
cout << arr1[i][j] << " ";
}
cout << endl;
}
cout << endl;
cout << "Elements in matrix 2: " << endl;
for (int i = 0; i < size_3; i++) {
for (int j = 0; j < size_3; j++) {
cout << arr2[i][j] << " ";
}
cout << endl;
}
cout << endl;
int** prod_arr = new int* [size_3];
for (int i = 0; i < size_3; i++) {
prod_arr[i] = new int[size_3];
}
for (int i = 0; i < size_3; i++) {
for (int j = 0; j < size_3; j++) {
prod_arr[i][j] = 0;
for (int k = 0; k < size_3; k++) {
prod_arr[i][j] += arr1[i][k] * arr2[k][j];
}
}
}
cout << "Elements in the product of 2 matrices: " << endl;
for (int i = 0; i < size_3; i++) {
for (int j = 0; j < size_3; j++) {
cout << prod_arr[i][j] << " ";
}
cout << endl;
}
}
However, I am gonna to use the function for the multiplication of the 2 matrices.
how could I move it to function, since the first array is static array, the second array is dynamic array.
I have try different way to use pointer , pass-by reference in the function, but still can't work.
My invalid code as below.
#include <iostream>
using namespace std;
int** function(int farr1, int farr2, int size3) {
int** prod_arr = new int* [size3];
for (int i = 0; i < size3; i++) {
prod_arr[i] = new int[size3];
}
for (int i = 0; i < size3; i++) {
for (int j = 0; j < size3; j++) {
prod_arr[i][j] = 0;
for (int k = 0; k < size3; k++) {
prod_arr[i][j] += farr1[i][k] * farr2[k][j];
}
return prod_arr[i][j];
}
}
}
int main()
{
int size_3 = 3;
//arr1 is a static array
int arr1[3][3] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };
//arr2 is a dynamic array
int** arr2 = new int* [size_3];
for (int i = 0; i < size_3; i++) {
arr2[i] = new int[size_3];
}
int val = 9;
for (int i = 0; i < size_3; i++) {
for (int j = 0; j < size_3; j++) {
arr2[i][j] = val--;
}
}
cout << "Elements in matrix 1: " << endl;
for (int i = 0; i < size_3; i++) {
for (int j = 0; j < size_3; j++) {
cout << arr1[i][j] << " ";
}
cout << endl;
}
cout << endl;
cout << "Elements in matrix 2: " << endl;
for (int i = 0; i < size_3; i++) {
for (int j = 0; j < size_3; j++) {
cout << arr2[i][j] << " ";
}
cout << endl;
}
cout << endl;
int** prod_arr = function(farr1, farr2, size_q3);
cout << "Elements in the product of 2 matrices: " << endl;
for (int i = 0; i < size_3; i++) {
for (int j = 0; j < size_3; j++) {
cout << prod_arr[i][j] << " ";
}
cout << endl;
}
cout << endl;
}
I want to use the function to execute the code.
I got 2 array, one is static and another is dynamic,
How to use pointer and pass to function with this different arrays.
Thanks a lot for your help.
Some C++ array examples to get you started :
A 2D dynamically array can be modeled as std::vector<std::vector<int>>
#include <array> // static array
#include <vector> // dynamic array, can resize at runtime
#include <iostream>
// https://en.cppreference.com/w/cpp/container/array
// accept a modifiable static array (content can be changed
// the & means by reference, the array will not get copied
// https://isocpp.org/wiki/faq/references
void func1(std::array<int, 4>& values)
{
values[2] = 3;
}
// array cannot be modified in body of func2 only used : const
void func2(const std::array<int, 4>& values)
{
std::cout << values[2] << "\n";
}
// https://en.cppreference.com/w/cpp/container/vector
// return a dynamically allocated array of integers
// it will have a size of 5 when returned
std::vector<int> get_values()
{
return std::vector<int>{1, 2, 3, 4, 5};
}
int main()
{
auto values = get_values();
values.push_back(6); // add another value
// https://en.cppreference.com/w/cpp/language/range-for
// prefer to use those if you don't need indices
// (which is not as often as you think)
for (const int value : values)
{
std::cout << value << " ";
}
return 0;
}

Merge sort program doesn't do anything to the array that I want to sort

I'm new to C++ and I'm trying to implement a merge sort but when I print my array in my main method it remains unmodified and I'm unsure of why that's the case. I tried printing the contents of the arrays that I split but it gave me values that I was unsure of where it was coming from.
#include <iostream>
#include <vector>
using namespace std;
void merge(vector<int> left, vector<int> right, vector<int> arr) {
int j = 0;
int k = 0;
int l = 0;
while (j < left.size() && k < right.size()) {
if (left[j] >= right[k]) {
arr[l] = right[k];
k += 1;
l += 1;
} else {
arr[l] = left[j];
j += 1;
l += 1;
}
}
if (j < left.size()) {
for (int i = j + k; i < arr.size(); i++) {
j += 1;
arr[i] = left[j];
}
}
if (k < right.size()) {
for (int i = j + k; i < arr.size(); i++) {
k += 1;
arr[i] = right[k];
}
}
}
void merge_sort(vector<int> arr) {
int n = arr.size();
if (n <2) {
return;
}
int mid = n / 2;
vector<int> left = vector<int>(arr.begin(), arr.end() - mid - 1);
for (int i : left) {
cout << i << " ";
}
cout << "\n";
vector<int> right = vector<int>(arr.begin() + mid, arr.end());
for (int i : right) {
cout << i << " ";
}
cout << "\n";
merge_sort(left);
merge_sort(right);
merge(left, right, arr);
}
int main() {
vector<int> arr = {3, 3, 4, 6, 42, 6, 2};
merge_sort(arr);
for (int i : arr) {
cout << i << " ";
}
return 0;
}
You are creating a copy of the vector when you pass it to merge_sort. Any changes made to arr in the function will not be visible in main.
Instead, you need to pass the vector by reference if you want the function to modify the argument:
void merge_sort(vector<int> &arr) {
// ^ by reference
Similarly for merge:
void merge(vector<int> &left, vector<int> &right, vector<int> &arr) {

Can't understand reason of the SIGTRAP in c++ code

I am writing some function for work with matrix.
I received correct output:
__11111111
__11111111
__333333333
__444444444444
But then program didn't stop and return invalid code
Process finished with exit code -1073741819 (0xC0000005)
How can i fix the error?
I tried debugger (gdb) and found out this:
Signal = SIGTRAP
And debugger presented me file new_allocator.h (attempt to deallocate nullptr)
// __p is not permitted to be a null pointer.
void
deallocate(pointer __p, size_type)
{ ::operator delete(__p); }
My code
#include <bits/stdc++.h>
using namespace std;
#define EPS 0.000001
int dualMatrix(vector<vector<double>> a) {
int n = a.size();
int m = a[0].size();
for (int col=0, row=0; col<m && row<n; ++col) {
int sel = row;
for (int i=row; i<n; ++i)
if (abs (a[i][col]) > abs(a[sel][col]))
sel = i;
if (abs(a[sel][col]) < EPS)
continue;
for (int i=col; i<=m; ++i)
swap(a[sel][i], a[row][i]);
cout << "__11111111\n";
for (int i=0; i<n; ++i)
if (i != row) {
if (a[row][col] == 0) {
cout << "DIVIDER IS ZERO" << endl;
return -1;
}
double c = a[i][col] / a[row][col];
for (int j=col; j<=m; ++j)
a[i][j] -= a[row][j] * c;
}
++row;
}
int rank = 0;
for (int i = 0; i < n; ++i) {
double temp = a[i][i];
if (temp == 0) {
cout << "Diagonal element is 0 at the row=" << i << endl;
rank = i;
break;
}
for (int j = 0; j < m; ++j) {
a[i][j] /= temp;
}
}
cout << "__333333333\n";
//printMatrix(a);
cout << "__444444444444\n";
return 0;
}
int main() {
vector<vector<double>> tmp {{1, 2, 3}, {3, 4, 5}};
dualMatrix(tmp);
cout << "__END" << endl;
return 0;
}
int m = a[0].size();
The size of the vector is m
for (int i=col; i<=m; ++i)
swap(a[sel][i], a[row][i]);
Here, i is outside the bounds of the vectorsa[sel] and a[row]. Accessing the vector outside of its bounds with the subscript operator has undefined behaviour.
Same here:
for (int j=col; j<=m; ++j)
a[i][j] -= a[row][j] * c;
How can i fix the error?
Don't access the vector outside of its bounds. If the size of the vector is 3, then the valid indices are 0, 1 and 2. If the size if m, then valid indices are 0, ..., m - 1

C++ multiplying matrices using dynamically allocated memory

I am trying to write a function in C++ that multiplies two matrices A, B which have been dynamically allocated. I am currently trying to get the multiplication code working, then I will attempt to turn it into a function. Right now I am getting an error of sorts; "segmentation fault (core dumped)". I have narrowed it down to the multiplication part of my code but I have no idea what is wrong with it. Can someone help me please? My code is shown below.
#include <iostream>
#include <cassert>
int main()
{
int rowsA = 5; // number of rows
int colsA= 3; // number of coloumns
// dynamically allocating A
double** A;
A = new double* [rowsA];
A[0] = new double [rowsA*colsA];
for (int i = 1; i < rowsA; i++)
{
A[i] = A[i-1] + colsA;
}
// Storing elements of matrix A
for(int i = 0; i < rowsA; ++i)
{
for(int j = 0; j < colsA; ++j)
{
std::cout << "Enter element A" << i + 1 << j + 1 << " : ";
std::cin >> A[i][j];
}
}
int rowsB = 3; // number of rows
int colsB = 5; // number of coloumns
// dynamically allocating B
double** B;
B = new double* [rowsB];
B[0] = new double [rowsB*colsB];
for (int i = 1; i < rowsB; i++)
{
B[i] = B[i-1] + colsB;
}
// Storing elements of matrix B
for(int i = 0; i < rowsB; ++i)
{
for(int j = 0; j < colsB; ++j)
{
std::cout << "Enter element B" << i + 1 << j + 1 << " : ";
std::cin >> B[i][j];
}
}
// checking matrix multiplication qualification
assert(colsA == rowsB);
// dynamically allocating C
double** C;
C = new double* [rowsA];
C[0] = new double [rowsA*colsB];
for (int i = 1; i < rowsA; i++)
{
C[i] = C[i-1] + colsB;
}
// Initializing elements of matrix C to 0
for(int i = 0; i < rowsA; ++i)
{
for(int j = 0; j < colsB; ++j)
{
C[i][j]=0;
}
}
// multiplication
for(int i = 0; i < rowsA; ++i)
{
for(int j = 0; j < colsB; ++j)
{
for(int k = 0; k < colsB; ++k)
{
C[i][j] += A[i][k] * B[k][j];
}
}
}
// Displaying the multiplication of matrices A, B
std::cout<< "Matrix C: " << std::endl;
for(int i = 0; i < rowsA; ++i)
{
for(int j = 0; j < colsB; ++j)
{
std::cout << " " << C[i][j];
if(j == colsB-1)
{
std::cout << std::endl;
}
}
}
// deallocation
delete[] C[0];
delete[] C;
delete[] B[0];
delete[] B;
delete[] A[0];
delete[] A;
}
First, you say you are allocating the matrix properly but I'm not seeing any proof of that. You are allocating an array of pointers and only initializing the first index.. A[0] for example. This is incorrect. You need to allocate EACH ROW.
You have:
double** A;
A = new double* [rowsA];
A[0] = new double [rowsA*colsA]; //Incorrect. You only allocated A[0].
You need to allocate A[0] through A[rowsA - 1]..
Next, your multiplication loop (the inner most loop) is incorrect. It should be:
Iterate ColsA for that inner loop.
You have:
for(int i = 0; i < rowsA; ++i)
{
for(int j = 0; j < colsB; ++j)
{
for(int k = 0; k < colsB; ++k) //ColsB is incorrect. Should be colsA..
{
C[i][j] += A[i][k] * B[k][j]; //Segfaults here due to bad iteration..
}
}
}
The following would be correct:
#include <iostream>
#include <cassert>
double** create_matrix(int rows, int cols)
{
double** mat = new double* [rows]; //Allocate rows.
for (int i = 0; i < rows; ++i)
{
mat[i] = new double[cols](); //Allocate each row and zero initialize..
}
return mat;
}
void destroy_matrix(double** &mat, int rows)
{
if (mat)
{
for (int i = 0; i < rows; ++i)
{
delete[] mat[i]; //delete each row..
}
delete[] mat; //delete the rows..
mat = nullptr;
}
}
int main()
{
int rowsA = 5; // number of rows
int colsA= 3; // number of coloumns
double** matA = create_matrix(rowsA, colsA);
int rowsB = 3; // number of rows
int colsB = 5; // number of coloumns
double** matB = create_matrix(rowsB, colsB);
//Checking matrix multiplication qualification
assert(colsA == rowsB);
double** matC = create_matrix(rowsA, colsB);
//Multiplication
for(int i = 0; i < rowsA; ++i)
{
for(int j = 0; j < colsB; ++j)
{
for(int k = 0; k < colsA; ++k) //ColsA..
{
matC[i][j] += matA[i][k] * matB[k][j];
}
}
}
//Clean up..
destroy_matrix(matA, rowsA);
destroy_matrix(matB, rowsB);
destroy_matrix(matC, rowsA);
}

Recursion of for's

I'm tried to figure out how to do it for quite of time and its not working as intended; I'm writing a code where there is 1 to k numbers, I need to find all possible combination without repeats. e.g. for 3: 1, 2, 3, 12, 13.
Example for counting 4-digits numbers with 1, 2, 3, 4, 5.
int k = 5;
for (int p = 0; p < k; p++)
{
for (int i = p+1; i < k; i++)
{
for (int j = i + 1; j < k; j++)
{
for (int h = j + 1; h < k; h++)
{
cout << p + 1 << i + 1 << j + 1 << h + 1 << endl;
}
}
}
}
And there is example for 3-digits number with 1, 2, 3.
int k = 4
for (int p = 0; p < k; p++)
{
for (int i = p+1; i < k; i++)
{
for (int j = i + 1; j < k; j++)
{
cout << p + 1 << i + 1 << j + 1 << endl;
}
}
}
I think that to count n-digits possible position without repeat i need n for's.
And i don't know how to do it without recursion which don't work when i do it.
My goal to get recursion which will count and print possible positions for n-digits.
I did recursion to count possibility myself, but love you guys for all your help.
My recursion is
void col(int ilosc)
{
static int st;
for (int i = st++; i < k; i++)
{
if (ilosc > 1)
col(ilosc - 1);
else
sposob++;
}
}
where ilosc is digits number and sposob is count of possible positions numbers.
NOTE: sposob and k is global variables.
I am not sure whether recursion is the best choice here, but you could do it like this:
typedef std::vector<int> IV;
IV getFirst(int k){
IV res;
for (int i=0;i<k-1;i++){res.push_back(i+1);}
return res;
}
bool getNext(IV& numbers,int i){
if (i==-1){return false;} // end of recursion
if (numbers[i]>i+1){return getNext(numbers,i-1);}
numbers[i]++;
return true;
}
bool getNext(IV& numbers){ // start of recursion
return getNext(numbers,numbers.size()-1);
}
int main() {
IV numbers = getFirst(5);
for (int i=0;i<numbers.size();i++){std::cout << numbers[i];}
std::cout << std::endl;
while(getNext(numbers)){
for (int i=0;i<numbers.size();i++){std::cout << numbers[i];}
std::cout << std::endl;
}
}
I think this will get you pretty close. I have an occasional repeat here, but this should set you on the right path.
const int max_depth = 5; // How long your string is
const int max_digit = 3; // Max digit you are counting to
int *nums = new int [max_depth];
void recurse_count(int depth)
{
if (depth < max_depth)
{
for(int i = depth; i <= depth+1; i++)
{
nums[depth] = i;
recurse_count(i+1);
}
}
else
{
for (int j = 0; j < max_depth; j++)
cout<<nums[j]+1;
cout<<endl;
}
}
int main()
{
recurse_count(0);
return 0;
}
My approach (still too early in the evening probably, I had problems with it)
namespace detail
{
void recurse_hlp(int min, int max, std::vector<int> vals, std::function<void(const std::vector<int>&)> f, std::size_t ptr)
{
if (ptr == vals.size())
f(vals);
else
{
for (int i = min; i <= max; ++i)
{
vals[ptr] = i;
recurse_hlp(min, max, vals, f, ptr + 1);
}
}
}
}
void recurse(int min, int max, int count, std::function<void(const std::vector<int>&)> f)
{
std::vector<int> vals(count);
detail::recurse_hlp(min, max, vals, f, 0);
}
void print(const std::vector<int>& vals)
{
for (int v : vals)
std::cout << v << " ";
std::cout << std::endl;
}
int main()
{
recurse(0, 5, 3, &print);
}
recurse gets a function accepting std::vector<int>, which contains all numbers from min to max up to count places.