0% found this document useful (0 votes)
9 views23 pages

Dynamic Memory Management

Dynamic memory Allocation DSA

Uploaded by

lokaprasaad.v.s
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views23 pages

Dynamic Memory Management

Dynamic memory Allocation DSA

Uploaded by

lokaprasaad.v.s
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

Go, change the

world

Dynamic Memory
Management
Go, change the
world

Memory Allocation

Two Types
•Static Memory Allocation
•Dynamic Memory Allocation

2
Go, change the
world

Static Memory Allocation


int students[1000];

•Until now, we have only learned about static memory


allocation
•Memory is allocated at compilation time
•Declaration of large memory variables (arrays) must be
determined before the program is excuted(compile time)
Go, change the
world
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

4
Go, change the
world

Static Memory Allocation


Static – Done by the compiler automatically (implicitly).
Global variables or objects -- memory is allocated at the start
of the program, and freed when program exits; alive
throughout program execution
• Can be access anywhere in the program.
Local variables (inside a routine) – memory is allocated when
the routine starts and freed when the routine returns.
• A local variable cannot be accessed from another routine.
Allocation and free are done implicitly.
No need to explicitly manage memory is nice (easy to work
with), but has limitations!
Using static allocation, the array size must be fixed.
Consider the grade roster for the class? What is the
number of people in the class?
Go, change the
world
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

6
Go, change the
world

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
• free

7
Go, change the
world
DYANMIC MEMORY
ALLOCATION

• Memory Allocation/De allocation during Run time


or Execution time
• We can “ask” for memory while the program is
running.
• We (Programmer) can allocate and release memory!
• More powerful programming ability (also more
potential for errors!)
Go, change the
world
Difference between Static and Dynamic Memory Allocation
STATIC MEMORY ALLOCATION DYNAMIC MEMORY ALLOCATION

Memory is allocated before the execution of the Memory is allocated during the execution of the
program begins (During Compilation). program.
Variables remain permanently allocated. Allocated only when program unit is active.
In this type of allocation Memory cannot be In this type of allocation Memory can be
resized after the initial allocation. dynamically expanded and shrunk as necessary.

Implemented using stacks. Implemented using heap.


Faster execution than Dynamic. Slower execution than static.
It is less efficient than Dynamic allocation strategy. It is more efficient than Static allocation strategy.

Implementation of this type of allocation is simple. Implementation of this type of allocation is


complicated.
Memory cannot be reuse when it is no longer Memory can be freed when it is no longer needed
needed. & reuse or reallocate during execution.
Go, change the

C Dynamic Memory Management world

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
Go, change the

malloc world

•The malloc (memory allocate) function is used to allocate a


contiguous block of memory from heap.
•If the memory allocation is successful, it returns a pointer to the
allocated block as a void pointer; otherwise, it returns a NULL
pointer.
•The prototype of this function is
void* malloc(size_t size)

•The malloc function has only one argument, the size (in bytes) of
the memory block to be allocated.
•Note that size_t is a type, also defined in stdlib.h, which is used
to declare the sizes of memory objects
•should be careful while using the malloc function as the allocated
memory block is uninitialized, i. e., it contains garbage values.

E.g., int* p = (int *)malloc(sizeof(int));


Go, change the

malloc world

•As different C implementations may have differences in data type


sizes, it is a good idea to use the sizeof operator to determine the
size of the desired data type and hence the size of the memory
block to be allocated.

•Typecast the void pointer returned by these functions to a pointer


of appropriate type.

Example :
Dynamically allocate a memory block to store 50 integers as shown
below.
int *p; /* pointer to the memory block to be allocated */

p= (int*) malloc(50 * sizeof(int)); /* alloc memory*/


Go, change the

malloc world

•It is a good idea to ensure, before continuing with program


execution, that the memory allocation was successful, i. e., the
pointer value returned is not NULL as shown below.

Int *p;
p= (int*) malloc(50 * sizeof(int)); /* alloc memory*/

if (p == NULL)
{
printf(“Error: Out of memory …\n”);
exit(1); /*Error code 1 is used here to indicate
out of memory situation */
}
•Once memory is allocated, this dynamically allocated array can be
used as a regular array. Thus, the ith element of array p in the
above example can be accessed as p [i].
Go, change the

calloc world

The calloc function is similar to malloc. However, it has two


parameters that specify the number of items to be allocated and the
size of each item
Prototype:
void* calloc(size_t n_items, size_t size)

Returns a pointer to space for array of n_items objects of size


size
… or NULL if the request cannot be satisfied
Bytes are initialized to 0

E.g., int * p= (int *)calloc(10,sizeof(int))


Go, change the

calloc world

•Another difference is that the calloc initializes the allocated


memory block to zero.
• This is useful in several situations where we require arrays
initialized to zero.
•It is also useful while allocating a pointer array to ensure
that the pointers will not have garbage values.
Go, change the
Releasing(De allocating) the Allocated world

Space: free
• An allocated block can be returned to the system for future use
by using the free function
• The deallocation actually returns that memory block to the
system heap.
• The prototype of free function is
void free(void * ptr)
will cause the program to give back the block to the heap (or free
memory). The argument ptr to free is any address that was
returned by a prior call to malloc.
•Deallocate the space pointed to by the pointer ptr
•Do nothing if ptr is NULL
•Note that no size needs to be mentioned for the allocated block,
the system remembers it for each pointer returned
16
crealloc Go, change the
world
•Size of dynamically allocated memory can be changed by using
realloc().
•The realloc (reallocate) function is used to adjust the size of a
dynamically allocated memory block.
• If required, the block is reallocated to a new location and the
existing contents are copied to it.
•Its prototype:
•void *realloc(void *ptr, size_t size);

•Realloc deallocates the old object pointed to by ptr and returns a


pointer to a new object that has the size specified by size.
•The contents of the new object is identical to that of the old object
prior to deallocation, up to the lesser of the new and old sizes.
• Any bytes in the new object beyond the size of the old object have
indeterminate values.
crealloc Go, change the
world

•Example
int *p;
p = (int*)malloc(50 * sizeof(int));

p = (int*)realloc(p,100);

free(p)
Go, change the
world
Go, change the
Diffrence between malloc() and world

calloc()
• calloc() initializes the allocated memory with 0 value.
malloc() initializes the allocated memory with garbage
values.
• calloc :Number of arguments is 2
malloc: Number of argument is 1
• Syntax :
calloc :
(cast_type *)calloc(blocks , size_of_block);
malloc:
(cast_type *)malloc(Size_in_bytes);

20
Go, change the
Memory Leaks world

• Memory leaks refer to memory that has been


allocated by an application, but not properly released
back once that memory is no longer needed.
• Many systems have multiple applications running on
their systems and programming errors usually result in
“memory leaks”.
• Memory leaks may not affect the functionality of the
application, but left unattended in a system, memory
leaks can cause the machine to crash.
• This is why, servers restart often to avoid them to from
going down.
• Programmers typically allocate memory and then
somehow may lose the reference to that memory
block.
Go, change the
Memory Leaks world

Example:
int A[n],i=0;

for (i=0;i<n;i++)
A[i] = random();

int* B = malloc(2*n);

B = A;
Go, change the
world

Example
int* A = malloc(4*sizeof(int));
int *B = A;

free(B);

You might also like