malloc - Devbhoomi

FREE JOB ALERT & ONLINE TUTORIALS

Hot

Post Top Ad

Sunday 5 November 2017

malloc

The name malloc stands for "memory allocation". The function malloc() reserves a block of memory of specified size and return a pointer of type void which can be casted into pointer of any form.
Syntax :

    void * malloc (size_t size);
size_t : stores only positive integer value, you can think of this particular datatype as unsigned integer datatype.
size cannot be negative , it can be either positive or zero value.
Malloc return a void pointer that gives us the address of the first byte in the block of memory that it allocates.
Example :

    void *malloc(2*sizeof(int)); //(no of elements * size of one unit)
this will store 2 * 4 = 8 byte on the memory say from address 201 to 208, ie. It allocates a block of memory for array of 2 integer , each of 4 byte
Value1Value2
201205
so the malloc will return void ptr to the address of the first byte i.e 201.
if we want to store values at these addresses.
  • As malloc return void ptr, and void ptr cannot be de-referenced, so we cannot directly assign the values as *p = 2;
  • void ptr can be typecasted into a pointer type of particular datatype and then it is used.
  • Inorder to use this block of memory we first need to typecast this void pointer of some datatype like this
Syntax :

    datatype *ptr=(cast-type*)malloc(byte-size)
    pointer = (type) malloc (size in bytes);


Example :

    ptr=(int*)malloc(2*sizeof(int));//2*4=8bytes

By asking memory block of 2 integers, we are basically creating an array of integers with 2 elements.

Assigning values to the address :

    ptr = 2; // this will assign value at the address say 201

    (ptr + 1) = 3; // this will assign value at the address 205


Getting the address

    &ptr[0] to get the address of first element and &ptr[1] to get the address of second element.

To access the values stored at the addresses

    *ptr will give the value as 2
    *(ptr + 1) will give the value 3

We can use ptr[0] to get the value 2 and ptr[1] to get the value 3.

To get next element in the array, you can increment the pointer.

Example :

    #include <stdio.h>
    #include <stdlib.h>
    void main()
    {
    int n,i,*ptr,sum=0;

    printf("Enter number of elements: ");
    scanf("%d",&n);

    ptr=(int*)malloc(n*sizeof(int)); //memory allocated using malloc

    if(ptr==NULL)
    {
    printf("Requested size of memory is unavailable ");
    exit(0);
    }

    printf("Enter elements of array: ");
    for(i=0;i<n;++i)
    {
    scanf("%d",ptr+i);
    sum+=*(ptr+i);
    }
    printf("Sum=%d",sum);
    }


Output :
Enter number of elements: 4
Enter elements of array:
5
5
5
5
Sum=20

No comments:

Post a Comment

Post Top Ad