Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 10-1: Dynamic Memory Allocation

Similar presentations


Presentation on theme: "Chapter 10-1: Dynamic Memory Allocation"— Presentation transcript:

1 Chapter 10-1: Dynamic Memory Allocation

2 Introduction Dynamic memory allocation allows our program to obtain more memory space while running, or to release it if it's not required. In simple terms, Dynamic memory allocation allows us to manually handle memory space for your program. Although, C language inherently does not have any technique to allocate memory dynamically, there are 4 library functions under "stdlib.h" for dynamic memory allocation.

3 Allocating Block of Memory: MALLOC
Function available on header file stdlib.h A block of memory may be allocated Allocated block of memory and return a pointer of type void. Means we can assign it to any other type of pointer Syntax ptr_name = (cast_type *)malloc(byte_size); Example 1

4 Multiple blocks of memory: CALLOC
Moemory allocating function normally used for requesting memory space for derived datatype like arrays and structure. Malloc allocates single block where as calloc allocates multiple block Syntax: ptr= (cast_type *) calloc (n, element-size) Example 2

5 MALLOC vs CALLOC First, is in the number of arguments. malloc() takes a single argument (memory required in bytes), while calloc() needs two arguments. Secondly, malloc() does not initialize the memory allocated, while calloc() initializes the allocated memory to ZERO. calloc() allocates a memory area, the length will be the product of its parameters. calloc fills the memory with ZERO's and returns a pointer to first byte. If it fails to locate enough space it returns a NULL pointer.

6 Releasing the used space
Function free() is used Example 2

7 Altering the size of Block: Realloc
ptr=malloc(size); ptr= relloc(ptr, newsize); The new size may be larger or smaller than the old size Not necessarily add into same block Compiler may find new place and copy old value plus add new space Ex: 3


Download ppt "Chapter 10-1: Dynamic Memory Allocation"

Similar presentations


Ads by Google