Right Click to Search

Monday, February 22, 2025

Malloc Function : Dynamic memory allocation


Malloc Function : Dynamic memory allocation

Syntax :
ptr = (data_type *)malloc(No_of_elements*sizeof(data_type));
Steps to Understand :
1 . (data_type *):
  • Type conversion or typecasting refers to changing an entity of one data type into another.
  • Example : if we assign the integer 4 to floating variable then internally it is assigned as 4.00
  • Similarly , Address of Block of memory is casted to address of Pointer .
2 . No_of_elements :
  • No_of_elements is nothing but the "No of elements Created at run time".
  • i.e Suppose we want to allocate space for 10 integer variable then No_of_elements = 10
3 . Sizeof(data_type)
  • Note Carefully : Sizeof is not function , it is Operator
  • Sizeof operator calculates the memory required for variable,data type etc
  • In malloc size of data_type is written .Data types specified in the first step must match with data type in this step.

Note : Example
ptr = (int *) malloc (10 * sizeof(int));
  • Malloc :
    • Header File : stdlib.h
    • Allocate 20 bytes of memory
    • Sizeof Returns the Size of Parameter specified 
    • 10 means allocate space at run time for 10 elements 
    • (int *)  means Typecasting i.e Address of Block of memory is casted to address of Pointer
    • On Success : 20 bytes will be allocated
    • On Fail : Returns NULL
    • Memory Address is assigned to Pointer ptr 
    • Clears allocated memory to garbage value

Tags / Keywords : | , ,

Stumble
Delicious
Technorati
Twitter
Facebook

0 Comments:

Post a Comment

Your Feedback :This is Growing Site and Your Feedback is important for Us to improve the Site performance & Quality of Content.Feel Free to contact and Please Provide Name & Contact Email

 

Learn C Programming Copyright © 2010 LKart Theme is Designed by Lasantha, Free Blogger Templates