Malloc function takes a size in bytes and returns a pointer to a block of free memory of that size. - C Memory

C examples for Memory:malloc

Introduction

This dynamically allocated memory is uninitialized and can only be accessed through pointers.

Demo Code

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

int main(void) {
  /* Dynamic memory allocation */
  char* ptr = (char*)malloc(sizeof(char) * 5);
}

The following code uses if statement to check if it has failed to allocate the memory.

char* ptr = malloc(sizeof(char) * 5);

if (ptr == NULL) {
  /* No memory allocated, exit function */
  return -1;
}

Related Tutorials