-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathallocation_deallocation.c
More file actions
112 lines (106 loc) · 2.55 KB
/
allocation_deallocation.c
File metadata and controls
112 lines (106 loc) · 2.55 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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
/*
Author: Tarun Jain
Roll Number: MT2015120
File: RTOS Assignment 1 - Question 1 -Allocation/Deallocation Functions
Problem Statement: Implement the malloc, free, calloc, realloc Function using your own Heap(Static array of 10240 Bytes)
*/
// Header Files
#include "heap_management.h"
// Realloc Function
void* my_realloc( void *p, size_t s)
{
// If NULL , Treat as Malloc Call
if( !p)
return (my_malloc(s));
// If Valid Address
if( valid(p))
{
void *xyz = my_malloc(s); // Getting Requested Space
if(!xyz) // If Space not available
return NULL;
copy_data(p , xyz); // Copy data of old block to new block
free(p); // Free Up the Old Block
return xyz; // Return New Block's address
}
return NULL; // If Invalid Address, return NULL
}
// Malloc Function
void* my_malloc( size_t s)
{
if( s == 0) // If Requested Size is Zero, Return NULL
return NULL;
struct block *b;
if( base) // If Heap is Already Created
{
traverse = (struct block *)base; // Set Traverse Pointer
b = find_block( s); // Find Appropriate Free Block
if(!b) // No Appropriate Free Block Found
{
b = extend_heap( s); // Extend Heap Because Free block not Found
if(!b) // Space Not Available
return NULL;
}
else // Appropriate Free Block Found
{
// Get Required Size for Your Block, Create Another Free block of Remaining size
if(( b->size - s) >= BLOCK_SIZE + 4)
split_block( b, s);
b -> free = 0; // Set Block as Occupied
}
}
else // First Time Malloc is Called. Heap is Created
{
b = extend_heap( s);
if(!b)
return NULL;
base = (void *)b; // Set Base
}
char *temp = (char *)b;
temp += BLOCK_SIZE;
return temp;
}
// Free Function
void free (void *x)
{
struct block *temp; // Just to Do Computation on Pointers
temp = (struct block*)x;
char *a = (char *)x;
a = a - BLOCK_SIZE;
temp = (struct block *)a;
if(!valid(x)) // If Invalid Address
{
printf("Invalid Free Operation");
return;
}
temp -> free = 1; // Free up the Block
// Merge Blocks
if( temp->prev && temp-> prev-> free)
temp = fusion(temp->prev);
if( temp->next)
{
if(temp->next->free)
fusion(temp);
}
else
{
if(temp->prev) // Last Node
temp->prev ->next = NULL;
else // Single Node Left
base = NULL;
limit = (void *)temp; // Update Break
}
}
// Calloc Implementation
void * my_calloc ( size_t number , size_t size )
{
size_t *new;
int s4 ,i;
new = my_malloc ( number * size );
if (new)
{
s4 = ( int) number;
for ( i = 0; i < s4 ; i++)
new[i] = 0;
}
return (new);
}