Memory Allocation - I
Memory Allocation - I
Memory Allocation
Prepared By:
Dr. Archana Sharma
[email protected]
Memory Management
Static
Stack
Heap
Storage /Memory Allocation
Memory allocation in programming is very
important for storing values when you assign them
to variables. The allocation is done either before or
at the time of program execution. This eventually
allocates memory for the variables declared by a
programmer via the compiler.
There are two memory management schemes for
the storage allocation of data –
3
Static & Dynamic Storage Management
Static Storage-Storage allocated at the time of
compilation. It can neither extended or returned to
the memory pool/ bank of free storage.
4
Static Storage
With static storage, the location of every variable
is fixed, allocated and known at compile-time. In
principle, every variable has a fixed constant
machine address.
5
Static variables are declared outside the main function and are
available throughout the program. These variables are allocated
memory at the time of program compilation. Global variables are
like static variables but are accessible from all the functions in
the program. Arrays are also allocated memory at the time of
program compilation, and their size is fixed.
The text area contains the program's machine instructions (i.e., the
executable code).
The stack (sometimes called the runtime stack) contains all the
automatic (i.e., non-static) variables.
Memory is allocated from and returned to the heap with the new
and delete operators, respectively.
Advantages of Static Memory Allocation:
Faster Access: Since the memory is allocated at compile
time, accessing static memory is faster compared to dynamic
memory. This is because the memory address is known at
the time of compilation.
calloc:
Resizing a previously allocated memory block is possible with the realloc (reallocate) function. It accepts two
arguments: the new size in bytes and a pointer to the current block. Upon successful reallocation, a pointer
to the newly allocated memory is returned. If not, NULL is returned. Here's an example:
1.int* ptr = (int*) calloc(5, sizeof(int)); // Allocates memory for an array of 5 integers
3. realloc:
The realloc (reallocate) function allows you to resize a previously allocated memory block. It takes a pointer
to the existing block and the new size in bytes as arguments. If reallocation is successful, it returns a pointer
to the reallocated memory. Otherwise, it returns NULL. Example usage:
16
Dynamic Storage Allocation
Two general approaches to dynamic storage
allocation:
Stack Allocation
Heap Allocation
17
Stack Allocation
Stack-allocated memory
A run-time stack is a simple and efficient way to
provide the storage needed for function calls.
When a function is called, memory is allocated for all of its parameters and local variables.
Each active function call has memory on the stack current function call on top)
When a function call terminates,
the memory is deallocated (“freed up”)
f()
main()
18
When a function is called, all storage needed for
the function is allocated on the stack in a section
called the activation record.
19
Heap Allocation
Heap-allocated memory
Memory consists of allocated areas and free areas (or holes).
The most flexible allocation scheme is heap-based allocation. Here, storage can be allocated and
de-allocated dynamically at arbitrary times during program execution. This will be more expensive than
either static or stack-based allocation global variables
Heap memory is allocated in a more complex way than stack memory.
20
Note: void * denotes a generic pointer type
21
Reallocating new heap memory
void *realloc(void *ptr, size_t new_size);
22
Deallocating heap memory
void free(void *pointer);
Given a pointer to previously allocated memory,
put the region back in the heap of unallocated memory
23
Checking for successful allocation
implementation of alloc:
#undef malloc
24
Storage Reclamation in Heap
How do we know when dynamically-allocated memory can be freed?
Easy when a chunk is only used in one place.
Reclamation is hard when information is shared: it can't be recycled until all of the users
are finished.
Usage is indicated by the presence of pointers to the data. Without a pointer, can't
access (can't find it).
25
Fixed Partitioning
Partition main memory into a set of
non-overlapping memory regions called
partitions.
Fixed partitions are of equal sizes.
It is the simplest storage maintenance method.
Leftover space in partition, after program
assignment, is called internal fragmentation.
Variable Partitioning
Degree of multiprogramming limited by number of partitions.
Variable-partition sizes for efficiency (sized to a given process’ needs).
Hole – block of available memory; holes of various size are scattered
throughout memory.
When a process arrives, it is allocated memory from a hole large enough to
accommodate it.
Process exiting frees its partition, adjacent free partitions combined.
Operating system maintains information about:
a) allocated partitions b) free partitions (hole)
Fixed Vs. Variable Sized Block Partition
As memory space utilization is concerned, the
variable sized block storage policy is preferred to
that of the fixed sized block storages.
Initially when there is no program in the memory ,
the entire memory is a block.
Memory Management
For the purpose of dynamic storage allocation, we
view memory as a single array broken into a series
of variable-size blocks, where some of the blocks
are free blocks and some are reserved blocks or
already allocated. The free blocks are linked
together to form a free list used for servicing
future memory requests.
When a memory request is received by the memory
manager, some block on the free list must be
found that is large enough to service the request.
If no such block is found, then the memory
manager must resort to a failure policy such as
garbage collection.
29
Memory Allocation Policies for Variable Sized
Blocks
First fit chooses the first block in the free list big enough to
satisfy the request, and split it.
Next fit is like first fit, except that the search for a fitting
block will start where the last one stopped, instead of at the
beginning of the free list.
Best fit chooses the smallest block bigger than the
requested one.
Worst fit chooses the biggest, with the aim of avoiding the
creation of too many small fragments – but doesn’t work well
in practice.
First Fit
In the first fit approach is to allocate the first free
partition or hole large enough which can
accommodate the process. It finishes after finding
the first suitable free partition.
Advantage
Fastest algorithm because it searches as little as
possible.
Disadvantage
The remaining unused memory areas left after
allocation become waste if it is too smaller. Thus
request for larger memory requirement cannot be
accomplished.
31
Best Fit
The best fit deals with allocating the smallest free
partition which meets the requirement of the
requesting process. This algorithm first searches
the entire list of free partitions and considers the
smallest hole that is adequate. It then tries to find
a hole which is close to actual process size
needed.
Advantage
Memory utilization is much better than first fit as it
searches the smallest free partition first available.
Disadvantage
It is slower and may even tend to produce small
free blocks that may be too small for subsequent
allocation.
32
Worst fit
In worst fit approach is to locate largest available
free portion so that the portion left will be big
enough to be useful. It is the reverse of best fit.
Advantage
Reduces the rate of production of small gaps.
Disadvantage
If a process requiring larger memory arrives at a
later stage then it cannot be accommodated as the
largest hole is already split and occupied.
33
Next fit
Next fit is a modified version of first fit. It begins
as first fit to find a free partition. When called next
time it starts searching from where it left off, not
from the beginning.
34
Disadvantage of Storage
Allocation Strategies:-
Next Fit > First Fit > Best Fit, Worst Fit.
Next Fit is the preferred one.
38
Storage
Compaction/Defragmentation
Storage compaction is another technique for
reclaiming free storage.
works by actually relocating some or all portions
into one end of the memory and thus combine the
holes into one large free.
There are two types of compaction :-
Incremental
Selective
39
Incremental Compaction:- All free blocks are
moved into one end of the memory to make a
large hole.
Selective Compaction:- Searches for a minimum
number of free blocks, the movements of which
yields a larger free hole. This hole may not be at
the end, it may be anywhere.
Garbage Collection
Garbage collection: storage isn't freed explicitly
(using free operation), but rather implicitly: just
delete pointers. When the system needs storage, it
searches through all of the pointers (must be able
to find them all!) and collects things that aren't
used.
If structures are circular then this is the only way
to reclaim space.
Garbage collectors typically compact memory,
moving objects to coalesce all free space.
Garbage collection is often expensive: 10-20% or
all CPU time in systems that use it.
41
Garbage Collection
Basic idea
keep track of what memory is referenced and when it is no longer
accessible, reclaim the memory
Example
linked list
Example
Obj1 Obj2 Obj3
head