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

Dynamic Memory Allocation

The document discusses dynamic memory allocation in C. It describes memory layout of a C program, the heap, stack, and functions like malloc, calloc, free and realloc to dynamically allocate and free memory at runtime. These functions allow programs to dynamically manage memory as needed during execution.

Uploaded by

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

Dynamic Memory Allocation

The document discusses dynamic memory allocation in C. It describes memory layout of a C program, the heap, stack, and functions like malloc, calloc, free and realloc to dynamically allocate and free memory at runtime. These functions allow programs to dynamically manage memory as needed during execution.

Uploaded by

Samyak Anand
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 21

Dynamic Memory

Allocation

1
Memory Layout of C Program
 In practical words, when we run any C-program, its
executable image is loaded into RAM of computer in an
organized manner.

2
Memory Layout of C Program
 1>Text or Code Segment :-Text segment
contains machine code of the compiled
program. The text segment of an executable
object file is often read-only segment that
prevents a program from being accidentally
modified.

3
Memory Layout of C Program
 2>Initialized Data Segment :-Initialized data
stores all global, static, constant, and
external variables (declared with extern
keyword ) that are initialized beforehand.
Data segment is not read-only, since the
values of the variables can be altered at run
time.

4
Memory Layout of C Program
 3>Uninitialized Data Segment (bss):-Data in
this segment is initialized to arithmetic 0
before the program starts executing.
Uninitialized data starts at the end of the data
segment and contains all global variables and
static variables that are initialized to 0 or do
not have explicit initialization in source code.

5
Memory Layout of C Program
 4>Heap:-Heap is the segment where
dynamic memory allocation usually takes
place. When some more memory need to be
allocated using malloc and calloc function,
heap grows upward. The Heap area is
shared by all shared libraries and
dynamically loaded modules in a process.

6
Memory Layout of C Program
 5>Stack:-Stack segment is used to store all local variables
and is used for passing arguments to the functions along
with the return address of the instruction which is to be
executed after the function call is over. Local variables have
a scope to the block which they are defined in, they are
created when control enters into the block. All recursive
function calls are added to stack.

 The stack and heap are traditionally located at opposite ends


of the process's virtual address space.

7
Problem with Arrays
 Sometimes
 Amount of data cannot be predicted beforehand
 Number of data items keeps changing during program execution
 Example: Search for an element in an array of N elements
 One solution: find the maximum possible value of N and allocate
an array of N elements
 Wasteful of memory space, as N may be much smaller in some
executions
 Example: maximum value of N may be 10,000, but a particular
run may need to search only among 100 elements
 Using array of size 10,000 always wastes memory in most

cases

8
Better Solution
 Dynamic memory allocation
 Know how much memory is needed after the program
is run
 Example: ask the user to enter from keyboard
 Dynamically allocate only the amount of memory
needed
 C provides functions to dynamically allocate
memory
 malloc, calloc, realloc

9
Memory Allocation Functions
 malloc
 Allocates requested number of bytes and returns a
pointer to the first byte of the allocated space
 calloc
 Allocates space for an array of elements, initializes
them to zero and then returns a pointer to the
memory.
 free
 Frees previously allocated space.
 realloc
 Modifies the size of previously allocated space.

10
Allocating a Block of Memory
 A block of memory can be allocated using the
function malloc
 Reserves a block of memory of specified size
and returns a pointer of type void
 The return pointer can be type-casted to any
pointer type
 General format:
type *p;
p = (type *) malloc (byte_size);

11
Example
p = (int *) malloc(100 * sizeof(int));

 A memory space equivalent to 100 times


the size of an int bytes is reserved
 The address of the first byte of the
allocated memory is assigned to the
pointer p of type int
p

400 bytes of space 12


Contd.
 cptr = (char *) malloc (20);

Allocates 20 bytes of space for the pointer cptr


of type char

Always use sizeof operator to find number of bytes for


a data type, as it can vary from machine to machine

13
Points to Note
 malloc always allocates a block of contiguous bytes
 The allocation can fail if sufficient contiguous
memory space is not available
 If it fails, malloc returns NULL

if ((p = (int *) malloc(100 * sizeof(int))) == NULL)


{
printf (“\n Memory cannot be allocated”);
exit();
}

14
Using the malloc’d Array
 Once the memory is allocated, it can be used with
pointers, or with array notation
 Example:
int *p, n, i;
scanf(“%d”, &n);
p = (int *) malloc (n * sizeof(int));
for (i=0; i<n; ++i)
scanf(“%d”, &p[i]);

The n integers allocated can be accessed as *p, *(p+1),


*(p+2),…, *(p+n-1) or just as p[0], p[1], p[2], …,p[n-1]
15
Releasing the Allocated Space:
free
 An allocated block can be returned to the
system for future use by using the free function
 General syntax:
free (ptr);
where ptr is a pointer to a memory block which
has been previously created using malloc
 Note that no size needs to be mentioned for the
allocated block, the system remembers it for
each pointer returned

16
Allocation Examples
p1 = malloc(4*sizeof(int))

p2 = malloc(5*sizeof(int))

p3 = malloc(6*sizeof(int))

free(p2)

p4 = malloc(2*sizeof(int))

17 Dynamic Memory Allocation


calloc()
 “calloc” or “contiguous allocation” method in C is used to
dynamically allocate the specified number of blocks of
memory of the specified type. it is very much similar to
malloc() but has two different points and these are:
 It initializes each block with a default value ‘0’.
 It has two parameters or arguments as compare to
malloc().
 If space is insufficient, allocation fails and returns a NULL
pointer.

18 Dynamic Memory Allocation


calloc()

19 Dynamic Memory Allocation


recalloc()
 “realloc” or “re-allocation” method in C is used to
dynamically change the memory allocation of a previously
allocated memory. In other words, if the memory
previously allocated with the help of malloc or calloc is
insufficient, realloc can be used to dynamically re-allocate
memory. re-allocation of memory maintains the already
present value and new blocks will be initialized with the
default garbage value.
 If space is insufficient, allocation fails and returns a NULL
pointer.

20 Dynamic Memory Allocation


recalloc()

21 Dynamic Memory Allocation

You might also like