-
Notifications
You must be signed in to change notification settings - Fork 7
/
smalloc.c
64 lines (54 loc) · 1.41 KB
/
smalloc.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
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
static const size_t VOLUME = sizeof(char) * 1024;
typedef struct pre_alloc_data
{
char *data;
size_t pos;
} pre_alloc_data;
pre_alloc_data *s;
char *smalloc(size_t size)
{
printf("smalloc size: %u\n", size);
if (size >= VOLUME)
{
printf("directly malloc size: %u\n", size);
return malloc(size);
}
if (s == NULL || s->pos + size >= VOLUME)
{
printf("pre malloc size: %u\n", VOLUME);
s = (pre_alloc_data *)malloc(sizeof(pre_alloc_data));
s->data = malloc(VOLUME);
s->pos = 0;
s->data[s->pos] = '\0';
}
char *p = (char *)s->data;
char *allocPos = &(p[s->pos]);
s->pos += size;
s->data[s->pos] = '\0';
return allocPos;
}
int main()
{
char *s = smalloc(sizeof(char) * 64);
printf("%s\n", s);
strcat(s, "hello");
strcat(s, ", ");
strcat(s, "world");
printf("%s\n", s);
char *t = smalloc(sizeof(char) * 512);
printf("%s\n", t);
strcat(t, "smalloc");
strcat(t, " ");
strcat(t, "good");
printf("%s\n", t);
printf("%s\n", s);
char *k = smalloc(sizeof(char) * 8192);
k[0] = '\0';
printf("%s\n", k);
strcat(k, "long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long string");
printf("%s\n", k);
return 0;
}