I have few lines of C++ code which has simple purpose – to store a matrix in two-dimensional array and not consume more memory, than is needed. This means I have to allocate memory for each number in matrix before putting it in matrix.
#include <cstdlib>
#include <cstdio>
using namespace std;
int main() {
int ** matrix;
matrix = (int**)malloc(sizeof(int*));
// Fill in the matrix
matrix[0] = (int *) malloc(3 * sizeof(int));
matrix[0][0] = 5;
matrix[0][1] = 10;
matrix[0][2] = 15;
matrix[1] = (int *) malloc(3 * sizeof(int));
matrix[1][0] = 2;
matrix[1][1] = 4;
matrix[1][2] = 6;
int i, n;
// Print the whole matrix
for (n = 0; n < 3; n++) {
for (i = 0; i < 3; i++) {
printf("%i\t", matrix[n][i]);
}
printf("\n");
}
return 0;
}
When i compile the code above and runs it, it crashes when printing the matrix:
3838 Segmentation fault (core dumped) sh “${SHFILE}”
The stackdump looks like this:
Exception: STATUS_ACCESS_VIOLATION at eip=0040126A
eax=00000000 ebx=00B0021C ecx=00000000 edx=00000000 esi=6123DBAA edi=61179FC3
ebp=0028CD18 esp=0028CCF0 program=C:\workspace\c\PA1_9\dist\Debug\Cygwin_4.x-Windows\pa1_9.exe, pid 3828, thread main
cs=0023 ds=002B es=002B fs=0053 gs=002B ss=002B
Stack trace:
Frame Function Args
0028CD18 0040126A (6123DBAA, 61179FC3, 0028CD58, 61006CD3)
0028CD58 61006CD3 (00000000, 0028CD94, 61006570, 7EFDE000)
End of stack trace
I guess there will be some troubles with pointers/values… but i don’t know where and why…
You’re code is almost correct, but the matrix allocation is wrong. You are allocating space to store a single
int *while you try to initialize two elements (matrix[0]andmatrix[1]) :The outer printing loop is wrong : there are only 2 “lines” in the matrix (with 3 columns each). The program will crash when you attempt to access
matrix[2]: