-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmm.c
More file actions
80 lines (70 loc) · 1.84 KB
/
mm.c
File metadata and controls
80 lines (70 loc) · 1.84 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
#include "mm.h"
#include <fcntl.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
void get_dump_file_name(char *buffer, size_t max_len) {
time_t raw_time;
struct tm *time_info;
time(&raw_time);
time_info = localtime(&raw_time);
strftime(buffer, max_len, "%Y_%m_%d_%H_%M_%S.log", time_info);
}
#define KB 1024
#define MB (1024 * 1024)
#ifndef MEMORY_TEST
#define DUMP_THRESHOLD (10 * MB)
#else
#define DUMP_THRESHOLD 0
#endif
MemoryManager *new_mm() {
MemoryManager *mm = (MemoryManager *)malloc(sizeof(MemoryManager));
mm->allocated_memory_size = 0;
mm->dump_file_fd = -1;
return mm;
}
void DUMP_MEMORY(MemoryManager *mm, const char *fmt, ...) {
if (fmt == NULL) {
return;
}
char *buf = NULL;
va_list args;
va_start(args, fmt);
int len = vsnprintf(NULL, 0, fmt, args);
va_end(args);
if (len < 0)
return;
buf = malloc(len + 1);
va_start(args, fmt);
vsnprintf(buf, len + 1, fmt, args);
va_end(args);
if (mm->dump_file_fd == -1) {
char *dump_file_name = (char *)malloc(sizeof(char) * 30);
get_dump_file_name(dump_file_name, 30);
mm->dump_file_fd =
open(dump_file_name, O_WRONLY | O_APPEND | O_CREAT, 0644);
}
if (mm->dump_file_fd == -1) {
return;
}
write(mm->dump_file_fd, buf, strlen(buf));
}
void memory_allocator(MemoryManager *mm, size_t size) {
mm->allocated_memory_size += size;
if (mm->allocated_memory_size >= DUMP_THRESHOLD) {
DUMP_MEMORY(mm, "Memory %d Byte\n", mm->allocated_memory_size);
}
}
void memory_deallocator(MemoryManager *mm, size_t size) {
if (mm->allocated_memory_size < size) {
mm->allocated_memory_size = 0;
} else {
mm->allocated_memory_size -= size;
}
if (mm->allocated_memory_size >= DUMP_MEMORY) {
DUMP_MEMORY(mm, "Memory %d Byte\n", mm->allocated_memory_size);
}
}