0% found this document useful (0 votes)
9 views

Memory Allocation - I

Uploaded by

darthvader3816
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Memory Allocation - I

Uploaded by

darthvader3816
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 44

UNIT-III

Memory Allocation

Prepared By:
Dr. Archana Sharma
[email protected]
Memory Management

Memory areas: In languages like C or


Java, the memory used by a program can be
allocated from three different areas:

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 –

1) Static Storage Management


II) Dynamic Storage Management

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.

Dynamic Storage- Allows user to allocate or


de-allocate memory as per the requirement during
the execution of programs . It is suitable to
multiprogramming environment also.

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.

One uses the word binding to mean an


association of a property with an entity in a
programming language. All binding of storage
locations to program names occur at compile-time
, is known as Early Binding. The bindings are
fixed and unchanged throughout run-time.

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).

Global variables are defined in global scope outside of any function


or object; static variables have the keyword static included as part
of their definition. The OS typically allocates the memory holding
global and static variables at program startup.

Segmented memory systems allocate the illustrated memory en


bloc, where it remains unused until the stack or heap grows into it.

Paged memory systems allocate the space in page-sized blocks


when the stack or heap grows.

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.

No Overhead: Static memory allocation does not require


any runtime overhead for memory allocation and
deallocation. This makes it more efficient than dynamic
memory allocation.

Persistent Data: Static variables and arrays retain their data


throughout the life of the program. This is useful when data
needs to be shared between different functions.
Disadvantages of Static Memory Allocation
Limited Flexibility: Static memory allocation is inflexible
because the size of the memory is fixed at compile
time. This means that if the size of the data structure
needs to be changed, the entire program needs to be
recompiled.

Wastage of Memory: If the size of the data structure is


not known in advance, static memory allocation can
result in the wastage of memory.

Limited Scope: Static variables are only accessible within


the function where they are defined, or globally if they
are defined outside of any function.
Dynamic Memory Allocation

Dynamic memory allocation is a memory management technique


that involves reserving memory for variables at runtime. This
means that memory is allocated and deallocated as required
during the program execution. Dynamic memory allocation is
commonly used for creating data structures such as linked lists,
trees, and dynamic arrays.
The process of allocating and releasing memory from
the heap is known as dynamic memory allocation. It
allows the programmer to manage memory explicitly,
providing the ability to create data structures of varying
sizes and adjust memory requirements dynamically.
Dynamic Memory Allocation Techniques:
In most programming languages, dynamic memory allocation is achieved through
dedicated functions provided by the language or standard library. Let's explore three
commonly used techniques:
malloc:
The malloc (memory allocation) function is used to allocate a specified number of bytes in
memory. When memory is allocated successfully, it returns a pointer to that block, otherwise it
returns NULL. By dividing the necessary number of elements by each one's individual size, the
block's size is calculated. For example:

int* ptr = (int*) malloc(5 * sizeof(int)); // Allocates memory for 5 integers

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:

1.int* ptr = (int*) malloc(5 * sizeof(int)); // Allocates memory for 5 integers


2.ptr = (int*) realloc(ptr, 10 * sizeof(int)); // Reallocates memory for 10 integers
Freeing Memory: delete Operator
Once we are done with the dynamically allocated memory, it is
essential to free it to avoid memory leaks. Memory that has been
allocated with the new operator is deallocated using the delete
operator. Here's the syntax:
delete pointerVariable;

For example, to deallocate the memory for the dynamically


allocated integer:
delete dynamicInt;
The new operator in C++ is used to allocate memory
on-demand. A pointer to the allocated memory is returned
along with the memory allocation of the given type. Here's
the syntax:

type* pointerVariable = new type;

1.int* dynamicInt = new int;


The new operator allocates memory on the heap, which is a
region of memory used for dynamic memory allocation. It
ensures that the allocated memory persists until explicitly
deallocated.
Static Vs. Dynamic Storage Allocation
The major difference between static and dynamic
memory allocations are:
Static Memory Allocation Dynamic Memory Allocation
variables get allocated permanently variables get allocated only if your
program unit gets active
Allocation is done before program Allocation is done during program
execution execution
It uses the static data structure for It uses the data structure called heap
implementing static allocation for implementing dynamic allocation
Less efficient More efficient

There is no memory reusability There is memory reusability and


memory can be freed when not
required

It uses Early Binding. It uses Late Binding.

16
Dynamic Storage Allocation
Two general approaches to dynamic storage
allocation:
Stack Allocation
Heap Allocation

Stack allocation (hierarchical): restricted, but


simple and efficient. A stack-based organization
keeps all the free space together in one place.
Heap allocation: more general, but less efficient,
more difficult to implement. Heap allocation must
be used when allocation and release are
unpredictable.

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”)

Ex: main() calls f(), g()


f() calls g()
g() recursively calls g()
g()

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.

The storage includes room for the return address,


the return value (possibly a pointer), actual
parameters passed to the function, and any
variables declared within the functionThe
activation record also holds locations for
temporary values, and pointers to other parts of
the stack (to facilitate access and deallocation).
On return from the function, the storage on the
stack is deallocated

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

Allocating new heap memory


void *malloc(size_t size);
Allocate a block of size bytes,
return a pointer to the block
(NULL if unable to allocate block)
void *calloc(size_t num_elements, size_t element_size);
Allocate a block of num_elements * element_size bytes,
initialize every byte to zero,
return pointer to the block
(NULL if unable to allocate block)

21
Reallocating new heap memory
void *realloc(void *ptr, size_t new_size);

Given a previously allocated block starting at ptr,


change the block size to new_size,
return pointer to resized block
If block size is increased, contents of old block may be copied to a completely different region
In this case, the pointer returned will be different from the ptr argument, and ptr will no
longer point to a valid memory region

If ptr is NULL, realloc is identical to malloc

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

Note: easy to forget to free memory when no


longer needed...
especially if you’re used to a language with “garbage collection” like Java
This is the source of the notorious “memory leak” problem
Difficult to trace – the program will run fine for some time, until suddenly there is no more memory!

23
Checking for successful allocation
implementation of alloc:
#undef malloc

void *alloc(size_t size) {


void *new_mem;
new_mem = malloc(size);
if (new_mem == NULL) exit(1);
return new_mem;
}
Nice solution – as long as “terminate the program”
is always the right response

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).

Two problems in reclamation:

Dangling pointers: storage is freed but referred to later. Pointer pointing to a


de-allocated memory.
Memory leaks: storage is not freed even though it is no longer needed .

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:-

Encounter the problem of memory


fragmentation, which never occurs in the case of
Fixed size request.
Another problem with dynamic storage allocation
systems is the areas of free memory(memory
holes) are interspersed with the actively used
partitions throughout the memory.
Memory Fragmentation
Fragmentation is encountered when the free
memory space is broken into little pieces as
processes are loaded and removed from
memory.
Fragmentation is of two types:
External fragmentation
Internal fragmentation

Fragmentation is major problem in dynamic


memory allocation
Memory fragmentation:
External fragmentation: Memory wasted outside allocated blocks
Internal fragmentation: Memory wasted inside allocated block. Results when memory allocated is
larger than memory requested.
The First fit algorithm is the best algorithm
among all because
It takes lesser time compare to the other
algorithms.
It produces bigger holes that can be used to load
other processes later on.
It is easiest to implement.

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

next next next


tail

Assume programmer does the following


obj1.next = obj2.next;

Obj1 Obj2 Obj3


head

next next next


tail
Example
Now there is no way for programmer to
reference obj2
it’s garbage

In system without garbage collection this is


called a memory leak
location can’t be used but can’t be reallocated
waste of memory and can eventually crash a program

In system with garbage collection this chunk


will be found and reclaimed

You might also like