Malloc

malloc() , calloc() and realloc() are memory management-related functions which are responsible for dynamic allocation of memory.

malloc():

  • malloc() stands for memory allocation, which allocates a contiguous block of memory dynamically.
  • It allocates memory space of a specified size and returns the base/starting address of the memory block or returns NULL in case of failure.
  • The pointer returned is of type void hence we can typecast such pointer to any type as per to need.
  • The memory allocated is uninitialized and hence contains garbage values

Syntax:

(void* ) malloc (size_t n)

Where size_t n is the number of bytes to be allocated size_t is always an unsigned integer.

Example:

int *ptr = ( int *) malloc (50)

50 bytes of memory will be reserved and the address of the first byte of reserved space will be assigned to the pointer ptr of type int.

Sample Program:

#include<stdio.h>
//To use malloc function in our program
#include<stdlib.h>

int main()
{
    int *ptr;
    ptr = malloc (sizeof(int));

    if (ptr != NULL)
    {
        printf ("Memory created successfully\n");
        printf ("\n The returned address is: %p\n", ptr);
    }
    else
        printf ("\n Memory allocation failed\n");
    return 0;
}
Output:
Memory created successfully
The returned address is: 0x79b010   

Sample program2:
This is to allocate memory to the structure

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct Emp
{
  int emp_no;
  char name[20];
  float sal;
 };
 
 int main()
 {
   struct Emp *ptr;
   ptr = (struct Emp*) malloc(sizeof(struct Emp));
   if (ptr == NULL)
     printf ("\n Memory allocation failed\n");
   else
   {
      ptr->emp_no = 20;
      strcpy (ptr->name, "techaccess");
      ptr->sal = 2345.7;
     printf("\n Name: %s employee no: %d sal is: %f \n", ptr->name, ptr->emp_no, ptr->sal);
   }
   return 0;
 }

Output:

Name: techaccess employee no: 20 sal is: 2345.699951

Diag-1:malloc

malloc in c

Relevant Posts:



Categories: C Language

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: