I've written this code in 2013 or 2014, I think. I've rediscovered it today in one of my folders, made some changes and now I'm left (and my 2013/2014 me as well) wondering how good it looks for other C programmers.
It's a simple dummy program that reads N and M from stdin
, then creates a matrix with those values as rows and columns with dynamic memory allocation, prints them, and then frees the memory. A rollback is made if malloc
fails.
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#define ERROR -1
#define SUCCESS 0
char welcome[] = "\tThis program \
gets the size of a matrix from stdin, messes around \
with it and then frees it.\n";
struct Matrix
{
int N;
int M;
int **values;
};
/**
* allocates memory for the matrix
*/
int allocateMatrix(struct Matrix *matrix, int n, int m)
{
printf("Allocating memory for matrix... (%d x %d)\n", n, m);
int i, j;
/* allocate rows */
matrix->values = malloc(n * sizeof(int*));
if (detectError(matrix->values)) {
return ERROR;
}
/* allocate columns */
for(i = 0; i < matrix->N; i++)
{
matrix->values[i] = malloc(m * sizeof(int));
/* handles errors */
if (detectError(matrix->values[i])) {
/* frees already allocated memory */
j = i-1;
for(; j >= 0; j--)
{
free(matrix->values[i]);
}
free(matrix->values);
return ERROR;
}
}
printf("%lu bytes of memory allocated! \n", (n * m * sizeof(int)));
}
/**
* gets the properties of the matrix
*/
int getMatrixProps(struct Matrix *matrix)
{
int n, m;
printf("\nWhat will be the size of our matrix? (N x M)\n");
scanf("%d %d", &n, &m);
matrix->N = n;
matrix->M = m;
return allocateMatrix(&(*matrix), n, m);
}
/**
* frees the memory requested
*/
void freeMatrixMem(struct Matrix *myMatrix)
{
int i;
for(i = 0; i < myMatrix->N; i++)
{
free(myMatrix->values[i]);
}
free(myMatrix->values);
}
/**
* populates and prints the matrix
*/
void dummyHandleMatrix(struct Matrix *myMatrix)
{
srand(time(NULL)); /* seeds random function */
int n, m;
printf("Populating matrix with random data... ");
for(n = 0; n < myMatrix->N; n++)
{
for(m = 0; m < myMatrix->M; m++)
{
int value = rand() % 50;
printf("%d ", value);
myMatrix->values[n][m] = value;
}
}
printf("\n");
printf("Matrix populated. Values are:\n[");
for(n = 0; n < myMatrix->N; n++)
{
for(m = 0; m < myMatrix->M; m++)
{
printf("%d, ", myMatrix->values[n][m]);
}
printf("\n");
}
printf("]\n");
}
int detectError(void *ptr) {
if (ptr == NULL)
{
printf("operation failed\n");
printf("%s\n", strerror(errno));
return ERROR;
}
return SUCCESS;
}
int main(int argc, char *argv[])
{
printf("%s", welcome);
struct Matrix myMatrix;
/* get size of the matrix and allocate memory for it */
if (getMatrixProps(&myMatrix) == ERROR) {
return ERROR;
}
/* populates it with random data and print to the screen */
dummyHandleMatrix(&myMatrix);
/* frees allocated memory */
printf("Freeing matrix memory!\n");
freeMatrixMem(&myMatrix);
printf("Memory freed.\n");
}