This repository has been archived on 2026-05-11. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
prog-103-p-03-2030/AcquiringLand/Fundamentals/leaks.c
T
2026-02-03 23:15:17 +01:00

52 lines
931 B
C

#include <stdlib.h>
#include <stdio.h>
int **allocate_matrix(int rows, int cols)
{
int **matrix = malloc(rows * sizeof(int *));
if (!matrix)
return NULL;
for (int i = 0; i < rows; i++)
{
matrix[i] = malloc(cols * sizeof(int));
if (!matrix[i])
{
for (int j = 0; j < i; j++)
free(matrix[j]);
free(matrix);
return NULL;
}
}
return matrix;
}
void free_matrix(int **matrix, int rows)
{
if (!matrix)
return;
free(matrix);
return;
}
int main(void)
{
int rows = 5;
int cols = 5;
int **matrix = allocate_matrix(rows, cols);
if (!matrix)
{
return EXIT_FAILURE;
}
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
matrix[i][j] = i * cols + j;
}
}
free_matrix(matrix, rows);
return EXIT_SUCCESS;
}