Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

malloc
c
memory allocation
dynamic

How to use "malloc" in C

Educative Answers Team

Memory allocation (malloc), is an in-built function in C. This function is used to assign a specified amount of memory for an array to be created. It also returns a pointer to the space allocated in memory using this function.

The need for malloc

In the world of programming where every space counts, there are numerous times when we only want an array to have a specific amount of space at run time. That is, we want to create an array occupying a particular amount of space, dynamically. We do this using malloc.

Syntax

We know what malloc returns and we know what it requires as an input, but how does the syntax of the function work. The illustration below shows that:

Note: malloc will return NULL if the memory specified is not available and hence, the allocation has failed

Examples

Now that we know how malloc is used and why it is needed, let’s look at a few code examples to see how it is used in the code.

#include<stdio.h>
#include <stdlib.h> 
int main() {

    int* ptr1;
    // We want ptr1 to store the space of 3 integers
    ptr1 = (int*) malloc (3 * sizeof(int));

    if(ptr1==NULL){
      printf("Memory not allocated. \n");
    }
    else{printf("Memory allocated succesfully. \n");
    // This statement shows where memory is allocated
    printf("The address of the pointer is:%u\n ", ptr1);
    
    // Here we assign values to the ptr1 created
    for(int i=0;i<3;i++){
      ptr1[i] = i;
    }
    // Printing the vlaues of ptr1 to show memory allocation is done
    for(int i=0;i<3;i++){
      printf("%d\n", ptr1[i]);
    }

    }
    
}

RELATED TAGS

malloc
c
memory allocation
dynamic
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring