C MEMORY MANAGEMENT FUNCTIONS

Ace your homework & exams now with Quizwiz!

free()

Frees or empties the previously allocated memory space. In dynamic memory allocation, you have to deallocate memory explicitly. If not done, you may encounter out of memory error. Dynamically allocated memory created with either calloc() or malloc() doesn't get freed on their own. You must explicitly use free() to release the space.

malloc() vs calloc()

Malloc() function is used to allocate a single block of memory space while the calloc() function is used to allocate multiple blocks of memory space. The malloc() function allocates memory and leaves the memory uninitialized with a garbage value. Whereas, the calloc() function allocates memory and initializes all bits to zero.

realloc()

Re-allocation. You can change the size of previously allocated memory using the realloc() function.

Dynamic memory allocation

Sometimes the size of the array you declared may be insufficient. To solve this issue, you can allocate memory manually during run-time. This is known as dynamic memory allocation

calloc()

Stands for contiguous allocation. Used to allocate multiple blocks of memory. Initializes the elements to zero and returns a pointer to the memory. Used to allocate the memory to complex data structures such as arrays and structures. Each block allocated by the calloc() function is of the same size.

malloc()

Stands for memory allocation. Allocates the memory of requested size and returns the pointer to the first byte of allocated space. The pointer returned is usually of type void. It means that we can assign malloc() function to any pointer.

Memory functions

To allocate memory dynamically, the library functions malloc(), calloc(), realloc() and free() are used. These functions are defined in the <stdlib.h> header file.

free() syntax

free(ptr); This statement frees the space allocated in the memory pointed by ptr.

calloc() syntax

ptr = (cast-type*) calloc(n, element-size); ptr = (float*) calloc(25, sizeof(float)); This statement allocates contiguous space in memory for 25 elements each with the size of the float.

malloc() syntax

ptr = (cast-type*) malloc(byte-size) ptr = (int*) malloc(100 * sizeof(int)); Since the size of int is 4 bytes, this statement will allocate 400 bytes of memory. And, the pointer ptr holds the address of the first byte in the allocated memory.

realloc() syntax

ptr = realloc(ptr, newSize); where ptr is reallocated with new size 'newSize'.


Related study sets

Intro to Film: Chapter 6: Cinematography

View Set

Cybersecurity Level 2 Study Guide

View Set

OEA Study guide - Social Studies

View Set

SUA Honors Chemistry 2014 Final exam

View Set

Physiology: Immune System Part 2

View Set

MKTG 300 - Exam 1 Review (Ch 1-3)

View Set

CHAPTER 1 TEST QUESTIONS AND ANSWERS!!!!

View Set