segmentation fault in functions about matrices in c - arrays

I implemented several functions about matrices related to arrays and pointers and everytime i run the code i get a segmentation fault.
It would be nice if someone could revise my code and maybe explain why this error occurs.
Function 1 should create a dynamically allocated matrix with the correspondent cols and rows. It should also initialize the elements to 0 (i have to use xmalloc and cannot use xcalloc) and return a pointer to the created matrix.
Function 2 gets an 1D-Array of rows * cols and should create a dynamically allocated matrix of these numbers.
Function 3 should print out a matrix.
Function 4 should free a created matrix.
This is my code
struct Matrix {
int rows; // number of rows
int cols; // number of columns
double** data; // a pointer to an array of n_rows pointers to rows; a row is an array of n_cols doubles
};
typedef struct Matrix Matrix;
/**
Creates a zero-initialized matrix of rows and columns matrix.
#param[in] n_rows number of rows
#param[in] n_cols number of columns
#return a pointer to an array of n_rows pointers to rows; a row is an array of n_cols doubles
*/
Matrix* make_matrix(int n_rows, int n_cols) {
double **m = xmalloc(n_rows * sizeof(double));
for(int row = 0; row < n_cols; row++){
m[row] = xmalloc(n_cols * sizeof(double));
}
Matrix matrixx = {n_cols, n_rows, m};
Matrix *pointer;
pointer = &matrixx;
return pointer;
}
/**
Creates a zero-initialized matrix of rows and columns matrix.
#param[in] data an array of doubles, ordered row-wise
#param[in] n_rows number of rows
#param[in] n_cols number of columns
#return a pointer to an array of n_rows pointers to rows; a row is an array of n_cols doubles
*/
Matrix* copy_matrix(double* data, int n_rows, int n_cols) {
Matrix *pointer = make_matrix(n_rows,n_cols);
int k = 0;
double **Matrix = (double **)xmalloc(sizeof(double *) * n_rows);
for(int i = 0; i < n_rows; i++){
Matrix[i] = (double *)xmalloc(sizeof(double ) * n_cols);
}
do{
for(int i = 0; i < n_rows; i++){
for(int j = 0; j < n_cols; j++){
Matrix[i][j] = data[k];
k++;
}
}
}while (k < sizeof(data));
return pointer;
}
/**
#param[in] m the matrix to print
*/
void print_matrix(Matrix* m) {
for(int row = 0; row < m->rows; row++){
for(int column = 0; column < m->cols; column++){
printf("%.f ", m->data[row][column]);
}
println();
}
println();
}
//#param[in] m the matrix to free
void free_matrix(Matrix* m) {
for (int i = 0; i < m->cols; i++)
free(m->data[i]);
free(m->data);
free(m);
}
I tried to allocate the memory with xmalloc in function 1,2 and 4 but somehow this does not work out and i get a segmentation fault error

In the first line of the make_matrix function, you might want to use only one asterisk because two asterisks mean your pointing to another pointer and I don't see where another pointer would be there
try changing it from this:
double **m = xmalloc(n_rows * sizeof(double));
to this:
double *m = xmalloc(n_rows * sizeof(double));
if that doesn't work then than tell me I'll look at the code again and try to spot another error

Related

Using pointers and malloc alone, how to define 2D int array? mine seems doesnt work. (seg fault)

I want to declare 2D-array in .h file without given numbers of COLS nor ROWS (cause they are read somewhere from inside the main() )
I mean I could tried another way of doing this like below
if one of ROWS and COLS is given at the firsthand.
int COLS = 20;
int (*array)[COLS];
array = malloc((*array) * ROWS);
thus I tried like below:
below is 2d.h
int* a;
int** b;
int size;
below is test2d.c, inside int main(){}
read_size() //size value read from some file
a = malloc(sizeof(int) * size);
b = malloc(sizeof(*a) * size);
for(int i=0; i<size; i++){
for(int j=0; j<size; j++){
b[i][j] = i+j;
printf("ok");
}
}
//print all
should be printing all 0112 but the result is segmentation fault.
To allocate a 2D array you need to allocate the 2D pointer b, which you have done. After that you need to allocate memory for b[i] in a for loop as below
// cols and rows are input by user or other parts of program.
int **b;
b = malloc(sizeof(int*) * rows);
for(int i=0; i<rows; i++){
b[i] = malloc(sizeof(int) * cols);
}
The explanation for this is that b is an array of pointers to int. In each element of b you allocate an array of int. This gives you a 2D array.
If you want a rectangular (not jagged array), it's most efficient to allocate all the cells as a single block, then the row pointers can all point into that block:
#include <stdlib.h>
int **make_array(size_t height, size_t width)
{
/* assume this multiplication won't overflow size_t */
int *cells = malloc((sizeof *cells) * height * width);
int **rows = malloc((sizeof *rows) * height);
if (!rows || !cells) {
free(cells);
free(rows);
return 0;
}
/* now populate the array of pointers to rows */
for (size_t row = 0; row < height; ++row) {
rows[row] = cells + width * row;
}
return rows;
}
This also makes deallocation much simpler, as we no longer need a loop:
void free_array(int **a)
{
if (!a) return;
free(a[0]);
free(a);
}

Matrix addition in c using malloc not allowing full input

So my assignment is to add matrices (they don't have to be square but the two matrices will always be the same size) by dynamically allocating the space for a 2-D array, and I used a double pointer. My function to get the user-inputted matrices is as follows:
void matrixEntry(const int rowNum, const int colNum, const char
matrixNum, int** matrix) {
int i, j, k;
matrix = (int**) malloc(rowNum * sizeof(int*));
for (k = 0; k < rowNum; ++k) {
matrix[i] = (int*)malloc(colNum * sizeof(int));
}
printf("Enter Matrix %c\n", matrixNum);
for (i = 0; i < rowNum; ++i) {
for (j = 0; j < colNum; ++j) {
scanf("%d", &matrix[i][j]);
}
}
}
where I call it in main twice as such:
matrixEntry(rowNum, colNum, matA, matrixOne);
matrixEntry(rowNum, colNum, matB, matrixTwo);
However, when I run the program I'm only allowed to enter the first row of Matrix A before the program stops running. I think this is because I didn't allocate enough space for the 2nd row, but I'm not sure where my mistake is. My thought process when allocating the space was that
matrix = (int**) malloc(rowNum * sizeof(int*));
allocated the space for the rowNum number of rows, and then the for loop allocated the space for the number of columns. Is this correct?

Field within structure take random values

I'm new to C and I'm trying to define a matrix using a struct and some methods that will change the int** field of the struct. The matrix is supposed to be dynamically allocated and also resizable in how many rows it can have. When I run the program below and print out the values of the matrix in main, the matrix just have random values, not the ones inserted in genMatrix() and addRow(). What am I doing wrong? Very grateful for any help.
I define the struct like this:
typedef struct matrix {
int** matrix;
int rows;
int cols;
int capacity;
} matrix;
And then have the following methods that should change the field of the struct:
matrix* genMatrix() {
matrix* matrix = malloc(sizeof(matrix));
initMatrix(matrix, 100, 3, 200);
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
int row[] = {i+j, i*j, i-j};
addRow(matrix, row);
}
}
return matrix;
}
void initMatrix(matrix* matrix, int rows, int cols, int capacity) {
matrix->matrix = malloc(rows * sizeof(int*));
for (int i = 0; i < rows; i++) {
matrix->matrix[i] = malloc(cols * sizeof(int));
}
matrix->cols = cols;
matrix->rows = rows;
matrix->capacity = capacity;
}
void addRow(matrix* matrix, int* row) {
if (matrix->rows == matrix->capacity) {
matrix->capacity *= 2;
matrix->matrix = realloc(matrix->matrix, matrix->capacity * sizeof(int*));
}
matrix->matrix[matrix->rows++] = row;
}
And in main I call the function genMatrix and then print the result out, but get random values like 32691, -1240670624 etc.
int main() {
matrix* matrix = genMatrix();
}
WHen you try to add a row here:
int row[] = {i+j, i*j, i-j};
addRow(matrix, row);
the data you are adding is a temporary local variable. On the next loop iteration it will get overwritten and then when the loop exits it will go out of scope.
You need to allocate some memory for the new row data, e.g. using malloc:
int * row = malloc(3 * sizeof(int));
row[0] = i+j;
row[1] = i*j;
row[2] = i-j;
addRow(matrix, row);
Don't forget to free all these row allocations later when you're done with the matrix.
You are storing row, a local variable. This pointer ceases to be valid once its scope ends:
for (int j = 0; j < 10; j++) {
int row[] = {i+j, i*j, i-j};
addRow(matrix, row);
}
You must dynamically allocate memory for the row data, too.
row is a local variable.As soon as loop goes for new iteration data gets overwritten and after loop exits data goes out of scope .
So use
int * row = malloc(NumOfRows * sizeof(int));
and then row members.

How to dynamically allocate a contiguous block of memory for a 2D array

If I allocate a 2D array like this int a[N][N]; it will allocate a contiguous block of memory.
But if I try to do it dynamically like this :
int **a = malloc(rows * sizeof(int*));
for(int i = 0; i < rows; i++)
a[i] = malloc(cols * sizeof(int));
This maintains a unit stride between the elements in the rows, but this may not be the case between rows.
One solution is to convert from 2D to 1D, besides that, is there another way to do it?
If your array dimensions are known at compile time:
#define ROWS ...
#define COLS ...
int (*arr)[COLS] = malloc(sizeof *arr * ROWS);
if (arr)
{
// do stuff with arr[i][j]
free(arr);
}
If your array dimensions are not known at compile time, and you are using a C99 compiler or a C2011 compiler that supports variable length arrays:
size_t rows, cols;
// assign rows and cols
int (*arr)[cols] = malloc(sizeof *arr * rows);
if (arr)
{
// do stuff with arr[i][j]
free(arr);
}
If your array dimensions are not known at compile time, and you are not using a C99 compiler or a C2011 compiler that supports variable-length arrays:
size_t rows, cols;
// assign rows and cols
int *arr = malloc(sizeof *arr * rows * cols);
{
// do stuff with arr[i * rows + j]
free(arr);
}
In fact, n-dimensional arrays (allocated on the stack) are really just 1-dimension vectors. The multiple indexing is just syntactic sugar. But you can write an accessor function to emulate something like what you want:
int index_array(int *arr, size_t width, int x, int y)
{
return arr[x * width + y];
}
const size_t width = 3;
const size_t height = 2;
int *arr = malloc(width * height * sizeof(*arr));
// ... fill it with values, then access it:
int arr_1_1 = index_array(arr, width, 1, 1);
However, if you have C99 support, then declaring a pointer to an array is possible, and you can even use the syntactic sugar:
int (*arr)[width] = malloc(sizeof((*arr) * height);
arr[x][y] = 42;
Say you want to dynamically allocate a 2-dimensional integer array of ROWS rows and COLS columns. Then you can first allocate a continuous chunk of ROWS * COLS integers and then manually split it into ROWS rows. Without syntactic sugar, this reads
int *mem = malloc(ROWS * COLS * sizeof(int));
int **A = malloc(ROWS * sizeof(int*));
for(int i = 0; i < ROWS; i++)
A[i] = mem + COLS*i;
// use A[i][j]
and can be done more efficiently by avoiding the multiplication,
int *mem = malloc(ROWS * COLS * sizeof(int));
int **A = malloc(ROWS * sizeof(int*));
A[0] = mem;
for(int i = 1; i < ROWS; i++)
A[i] = A[i-1] + COLS;
// use A[i][j]
Finally, one could give up the extra pointer altogether,
int **A = malloc(ROWS * sizeof(int*));
A[0] = malloc(ROWS * COLS * sizeof(int));
for(int i = 1; i < ROWS; i++)
A[i] = A[i-1] + COLS;
// use A[i][j]
but there's an important GOTCHA! You would have to be careful to first deallocate A[0] and then A,
free(A[0]);
free(A); // if this were done first, then A[0] would be invalidated
The same idea can be extended to 3- or higher-dimensional arrays, although the code will get messy.
You can treat dynamically allocated memory as an array of a any dimension by accessing it in strides:
int * a = malloc(sizeof(int) * N1 * N2 * N3); // think "int[N1][N2][N3]"
a[i * N2 * N3 + j * N3 + k] = 10; // like "a[i, j, k]"
The best way is to allocate a pointer to an array,
int (*a)[cols] = malloc(rows * sizeof *a);
if (a == NULL) {
// alloc failure, handle or exit
}
for(int i = 0; i < rows; ++i) {
for(int j = 0; j < cols; ++j) {
a[i][j] = i+j;
}
}
If the compiler doesn't support variable length arrays, that only works if cols is a constant expression (but then you should upgrade your compiler anyway).
Excuse my lack of formatting or any mistakes, but this is from a cellphone.
I also encountered strides where I tried to use fwrite() to output using the int** variable as the src address.
One solution was to make use of two malloc() invocations:
#define HEIGHT 16
#define WIDTH 16
.
.
.
//allocate
int **data = malloc(HEIGHT * sizeof(int **));
int *realdata = malloc(HEIGHT * WIDTH * sizeof(int));
//manually index
for (int i = 0; i < HEIGHT; i++)
data[i] = &realdata[i * WIDTH];
//populate
int idx = 0;
for (int i = 0; i < HEIGHT; i++)
for (int j = 0; j < WIDTH; j++)
data[i][j] = idx++;
//select
int idx = 0;
for (int i = 0; i < HEIGHT; i++)
{
for (int j = 0; j < WIDTH; j++)
printf("%i, ", data[i][j]);
printf("/n");
}
//deallocate
.
.
.
You can typedef your array (for less headake) and then do something like that:
#include <stdlib.h>
#define N 10
typedef int A[N][N];
int main () {
A a; // on the stack
a[0][0]=1;
A *b=(A*)malloc (sizeof(A)); // on the heap
(*b)[0][0]=1;
}

How do we allocate a 2-D array using One malloc statement

I have been asked in an interview how do i allocate a 2-D array and below was my solution to it.
#include <stdlib.h>
int **array;
array = malloc(nrows * sizeof(int *));
for(i = 0; i < nrows; i++)
{
array[i] = malloc(ncolumns * sizeof(int));
if(array[i] == NULL)
{
fprintf(stderr, "out of memory\n");
exit or return
}
}
I thought I had done a good job but then he asked me to do it using one malloc() statement not two. I don't have any idea how to achieve it.
Can anyone suggest me some idea to do it in single malloc()?
Just compute the total amount of memory needed for both nrows row-pointers, and the actual data, add it all up, and do a single call:
int **array = malloc(nrows * sizeof *array + (nrows * (ncolumns * sizeof **array));
If you think this looks too complex, you can split it up and make it a bit self-documenting by naming the different terms of the size expression:
int **array; /* Declare this first so we can use it with sizeof. */
const size_t row_pointers_bytes = nrows * sizeof *array;
const size_t row_elements_bytes = ncolumns * sizeof **array;
array = malloc(row_pointers_bytes + nrows * row_elements_bytes);
You then need to go through and initialize the row pointers so that each row's pointer points at the first element for that particular row:
size_t i;
int * const data = array + nrows;
for(i = 0; i < nrows; i++)
array[i] = data + i * ncolumns;
Note that the resulting structure is subtly different from what you get if you do e.g. int array[nrows][ncolumns], because we have explicit row pointers, meaning that for an array allocated like this, there's no real requirement that all rows have the same number of columns.
It also means that an access like array[2][3] does something distinct from a similar-looking access into an actual 2d array. In this case, the innermost access happens first, and array[2] reads out a pointer from the 3rd element in array. That pointer is then treatet as the base of a (column) array, into which we index to get the fourth element.
In contrast, for something like
int array2[4][3];
which is a "packed" proper 2d array taking up just 12 integers' worth of space, an access like array[3][2] simply breaks down to adding an offset to the base address to get at the element.
int **array = malloc (nrows * sizeof(int *) + (nrows * (ncolumns * sizeof(int)));
This works because in C, arrays are just all the elements one after another as a bunch of bytes. There is no metadata or anything. malloc() does not know whether it is allocating for use as chars, ints or lines in an array.
Then, you have to initialize:
int *offs = &array[nrows]; /* same as int *offs = array + nrows; */
for (i = 0; i < nrows; i++, offs += ncolumns) {
array[i] = offs;
}
Here's another approach.
If you know the number of columns at compile time, you can do something like this:
#define COLS ... // integer value > 0
...
size_t rows;
int (*arr)[COLS];
... // get number of rows
arr = malloc(sizeof *arr * rows);
if (arr)
{
size_t i, j;
for (i = 0; i < rows; i++)
for (j = 0; j < COLS; j++)
arr[i][j] = ...;
}
If you're working in C99, you can use a pointer to a VLA:
size_t rows, cols;
... // get rows and cols
int (*arr)[cols] = malloc(sizeof *arr * rows);
if (arr)
{
size_t i, j;
for (i = 0; i < rows; i++)
for (j = 0; j < cols; j++)
arr[i][j] = ...;
}
How do we allocate a 2-D array using One malloc statement (?)
No answers, so far, allocate memory for a true 2D array.
int **array is a pointer to pointer to int. array is not a pointer to a 2D array.
int a[2][3] is an example of a true 2D array or array 2 of array 3 of int
To allocate memory for a true 2D array, with C99, use malloc() and save to a pointer to a variable-length array (VLA)
// Simply allocate and initialize in one line of code
int (*c)[nrows][ncolumns] = malloc(sizeof *c);
if (c == NULL) {
fprintf(stderr, "out of memory\n");
return;
}
// Use c
(*c)[1][2] = rand();
...
free(c);
Without VLA support, if the dimensions are constants, code can use
#define NROW 4
#define NCOL 5
int (*d)[NROW][NCOL] = malloc(sizeof *d);
You should be able to do this with (bit ugly with all the casting though):
int** array;
size_t pitch, ptrs, i;
char* base;
pitch = rows * sizeof(int);
ptrs = sizeof(int*) * rows;
array = (int**)malloc((columns * pitch) + ptrs);
base = (char*)array + ptrs;
for(i = 0; i < rows; i++)
{
array[i] = (int*)(base + (pitch * i));
}
I'm not a fan of this "array of pointers to array" to solve the multi dimension array paradigm. Always favored a single dimension array, at access the element with array[ row * cols + col]? No problems encapsulating everything in a class, and implementing a 'at' method.
If you insist on accessing the members of the array with this notation: Matrix[i][j], you can do a little C++ magic. #John solution tries to do it this way, but he requires the number of column to be known at compile time. With some C++ and overriding the operator[], you can get this completely:
class Row
{
private:
int* _p;
public:
Row( int* p ) { _p = p; }
int& operator[](int col) { return _p[col]; }
};
class Matrix
{
private:
int* _p;
int _cols;
public:
Matrix( int rows, int cols ) { _cols=cols; _p = (int*)malloc(rows*cols ); }
Row operator[](int row) { return _p + row*_cols; }
};
So now, you can use the Matrix object, for example to create a multiplication table:
Matrix mtrx(rows, cols);
for( i=0; i<rows; ++i ) {
for( j=0; j<rows; ++j ) {
mtrx[i][j] = i*j;
}
}
You should now that the optimizer is doing the right thing and there is no call function or any other kind of overhead. No constructor is called. As long as you don't move the Matrix between function, even the _cols variable isn't created. The statement mtrx[i][j] basically does mtrx[i*cols+j].
It can be done as follows:
#define NUM_ROWS 10
#define NUM_COLS 10
int main(int argc, char **argv)
{
char (*p)[NUM_COLS] = NULL;
p = malloc(NUM_ROWS * NUM_COLS);
memset(p, 81, NUM_ROWS * NUM_COLS);
p[2][3] = 'a';
for (int i = 0; i < NUM_ROWS; i++) {
for (int j = 0; j < NUM_COLS; j++) {
printf("%c\t", p[i][j]);
}
printf("\n");
}
} // end of main
You can allocate (row*column) * sizeof(int) bytes of memory using malloc.
Here is a code snippet to demonstrate.
int row = 3, col = 4;
int *arr = (int *)malloc(row * col * sizeof(int));
int i, j, count = 0;
for (i = 0; i < r; i++)
for (j = 0; j < c; j++)
*(arr + i*col + j) = ++count; //row major memory layout
for (i = 0; i < r; i++)
for (j = 0; j < c; j++)
printf("%d ", *(arr + i*col + j));

Resources