There are multiple issues with your program. Let me list all of them one by one.
- As mentioned in one of the comments, You are immediately
deallocating memory just after you allocated it. Definitely this
will result in a segmentation fault or memory access violation when
you access deallocated memory. - When you allocate the memory you are not
assigning the allocated memory pointers to global pointer
dynamicArray
instead you are creating a local variable with the
same name inside the functioninput_matrix
. As this pointer
variable scope ends inside the function you are losing the memory
allocated. Hence again you will face segmentation fault or memory
access violation insideprint_matrix
function. - Inside
print_matrix
function in inner for loop you are checking ifm==COLUMNS
to print new line, this will never happen since m is always less thanCOLUMNS
. - Finally, as the previous answer suggests when you are using C++, using a vector with smart pointers is a better choice than using array and raw pointers for better memory management.
Following snippet resolves those issues.
#include <iostream>
#include <string>
using namespace std;
int **dynamicArray ;
int ROWS, COLUMNS;
//---------------------------------
int input_matrix(int ROWS, int COLUMNS)
{
//---------------------------------------
//memory allocated for elements of rows.
dynamicArray = new int *[ROWS];
//memory allocated for elements of each column.
for (int i = 0; i < ROWS; i++)
dynamicArray[i] = new int [COLUMNS];
// cout<<"Input array values\n";
for (int i = 0; i < ROWS; i++)
{
for (int j = 0; j < COLUMNS; j++)
{
cin>>dynamicArray[i][j];
}
}
return 0;
}
void free_matrix_memory()
{
cout<<"freeing allocated memory\n";
//free the allocated memory
for (int i = 0; i < ROWS; i++)
delete[] dynamicArray[i];
delete[] dynamicArray;
//-------------------------------------
}
//---------------------------------------------
int print_matrix(int **Array)
{
cout<<"printing matrix\n";
for (int k = 0; k < ROWS; k++)
{
for (int m = 0; m < COLUMNS; m++)
cout << Array[k][m];
cout << "\n";
}
return 0;
}
//---------------------------------
int main()
{
cout<<"Row and column values\n";
cin>> ROWS;
cin>> COLUMNS;
input_matrix(ROWS, COLUMNS);
print_matrix(dynamicArray);
free_matrix_memory();
}
Still many improvements can be done for your such as avoiding global variables etc., I am leaving it up to you to do those improvements.
1
solved Exception thrown: read access violation. **dynamicArray** was 0x1118235. occurred