-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathblprint.c
More file actions
76 lines (69 loc) · 1.76 KB
/
blprint.c
File metadata and controls
76 lines (69 loc) · 1.76 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
//this is basic implementation which gives me the idea of how the malloc works,
//this is a simple program which uses a header with doubly linked list to allocate and free memory
//I extended this code in the main malloc.c , although this code does not cover
//all the basic things but gives us an idea of what's going on and how pointer's work.
#include<unistd.h>
#include<stddef.h>
#include<stdio.h>
typedef struct block_header{
size_t size;
int isfree;
struct block_header* next;
}block_header_t;
block_header_t *requestspace(size_t size){
block_header_t *block=sbrk(0);
void *request=sbrk(sizeof(block_header_t)+size);
if(request==(void*)-1)return NULL;
block->size=size;
block->isfree=0;
block->next=NULL;
return block;
}
static block_header_t *freelist=NULL;
block_header_t *findfreespace(size_t size){
block_header_t *curr=freelist;
while(curr){
if(curr->isfree && curr->size>=size){
return curr;
}
curr=curr->next;
}
return NULL;
}
void *mymalloc(size_t size){
if(size==0)return NULL;
block_header_t *block=findfreespace(size);
if(block){
block->isfree=0;
}else{
block=requestspace(size);
if(!block)return NULL;
if(!freelist)freelist=block;
else{
block_header_t *curr=freelist;
while(curr->next)curr=curr->next;
curr->next=block;
}
}
return (void*)(block+1);
}
void myfree(void* ptr){
if(!ptr)return;
block_header_t *block=(block_header_t*)ptr-1;
block->isfree=1;
}
int main(){
int* a=mymalloc(sizeof(int));
*a=234;
printf("a at %p\n",(void*)a);
myfree(a);
// printf("freed a");
int* b=mymalloc(sizeof(int));
// printf("allocated b");
*b=333;
printf("b at %p\n",(void*)b);
char* c=mymalloc(sizeof(char));
*c='h';
printf("c at %p\n",(void*)c);
return 0;
}