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-09 03:43:16 +01:00

57 lines
1.1 KiB
C

#include <stdlib.h>
#include <stdio.h>
int **allocate_matrix(int rows, int cols)
{
int **matrix = malloc(rows * sizeof(int *));//creation du tableau X hauteur
if (!matrix)
return NULL;
for (int i = 0; i < rows; i++)
{
matrix[i] = malloc(cols * sizeof(int));//creation des colonnes
//on free les cols si la matrice n'existe pas
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;
//ajout
for (int j = 0; j < rows; j ++)
free(matrix[j]);
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);
//free(matrix);
return EXIT_SUCCESS;
}