-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmemory_tests.c
More file actions
87 lines (76 loc) · 1.92 KB
/
Copy pathmemory_tests.c
File metadata and controls
87 lines (76 loc) · 1.92 KB
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
#include "memory_management.h"
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
int main()
{
// Test 1: Allocate and free memory
int *ptr1 = (int *)_malloc(sizeof(int));
assert(ptr1 != NULL);
*ptr1 = 42;
printf("Before: ");
printFreeList();
_free(ptr1);
printf("After: ");
printFreeList();
printf("Test 1 passed: Memory allocated and used successfully\n\n");
// Test 2: Allocate an array and free it
int *arr = (int *)_malloc(5 * sizeof(int));
assert(arr != NULL);
for (int i = 0; i < 5; ++i)
{
arr[i] = i * 2;
}
*ptr1 = 42;
printf("Before: ");
printFreeList();
_free(arr);
printf("After: ");
printFreeList();
printf("Test 2 passed: Array allocated and freed successfully\n\n");
// Test 3: Allocate and free memory in a loop
for (int i = 0; i < 1000; ++i)
{
char *ptr2 = (char *)_malloc(sizeof(char));
assert(ptr2 != NULL);
*ptr2 = 'y';
_free(ptr2);
}
printFreeList();
printf("Test 3 passed: Allocate and free in a loop successfully\n\n");
// Test 4: Allocate and free an array in a loop
int **ptr = (int **)_malloc(1000 * sizeof(int *));
assert(ptr != NULL);
for (int i = 0; i < 1000; ++i)
{
ptr[i] = (int *)_malloc(sizeof(int));
assert(ptr[i] != NULL);
*ptr[i] = i;
}
printf("Before: ");
printFreeList();
for (int i = 0; i < 1000; ++i)
{
_free(ptr[i]);
}
_free(ptr);
printf("After: ");
printFreeList();
printf("Test 4 passed: Allocate and free an array in a loop successfully\n\n");
// Test 5: Allocate a memory of size 0
int *ptr3 = (int *)_malloc(0);
assert(ptr3 == NULL);
printFreeList();
printf("Test 5 passed: Allocate a memory of size 0 successfully\n\n");
// Test 6: Free NULL pointer
int *ptr4 = NULL;
_free(ptr4);
printf("Test 6 passed: Free wild pointer successfully\n\n");
// Test 7: Double free
int *ptr5 = (int *)_malloc(sizeof(int));
int *ptr6 = ptr5;
_free(ptr5);
_free(ptr6);
printf("Test 7 passed: Judge double free successfully\n\n");
return 0;
}