-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmem_ops.c
93 lines (77 loc) · 1.73 KB
/
mem_ops.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
// Copyright Rares-Stefan Goidescu 312CAb 2023-2024
#include <stdio.h>
#include <stdlib.h>
/******************************PRIVATE FUNCTIONS******************************/
void handle_null_pointer(void *p)
{
if (!p) {
printf("Eroare la alocare\n");
exit(-1);
}
}
/******************************EXPORTED FUNCTIONS*****************************/
/*
Aceste functii aloca si elibereaza memorie dinamic.
Nu sunt sigur daca pot face o functie care sa poata aloca o matrice
cu elemente de orice tip (int/double/unsigned)
*/
unsigned int **allocate_matrix(int n, int m)
{
unsigned int **ptr = NULL;
ptr = malloc(n * sizeof(unsigned int *));
handle_null_pointer(ptr);
for (int i = 0; i < n; ++i) {
ptr[i] = malloc(m * sizeof(unsigned int));
handle_null_pointer(ptr[i]);
if (!ptr) {
for (int j = 0; j < i; j++)
free(ptr[j]);
free(ptr);
}
}
return ptr;
}
int **allocate_int_matrix(int n, int m)
{
int **ptr = NULL;
ptr = malloc(n * sizeof(int *));
handle_null_pointer(ptr);
for (int i = 0; i < n; ++i) {
ptr[i] = malloc(m * sizeof(int));
handle_null_pointer(ptr[i]);
if (!ptr) {
for (int j = 0; j < i; j++)
free(ptr[j]);
free(ptr);
}
}
return ptr;
}
double **allocate_double_matrix(int n, int m)
{
double **ptr = NULL;
ptr = malloc(n * sizeof(double *));
handle_null_pointer(ptr);
for (int i = 0; i < n; ++i) {
ptr[i] = malloc(m * sizeof(double));
handle_null_pointer(ptr[i]);
if (!ptr) {
for (int j = 0; j < i; j++)
free(ptr[j]);
free(ptr);
}
}
return ptr;
}
void deallocate_matrix(unsigned int **ptr, int n)
{
for (int i = 0; i < n; i++)
free(ptr[i]);
free(ptr);
}
void deallocate_double_matrix(double **ptr, int n)
{
for (int i = 0; i < n; i++)
free(ptr[i]);
free(ptr);
}