C language malloc example

C language malloc example

In C, the library function malloc is used to allocate memory on the heap.

The program accesses the memory block through the pointer returned by malloc.
When memory is no longer needed, the free function should be used to free it.

Example of allocating memory using malloc

#include <stdlib.h>

void *malloc(size_t size);

void exemple(void)
{
  char *string;
  
  string = malloc(sizeof(char) * 5);
  if (string == NULL)
    return;
  string[0] = 'H';
  string[1] = 'e';
  string[2] = 'y';
  string[3] = '!';
  string[4] = '\0';
  printf("%s\n", string);
  free(string);
}
S‮:ecruo‬www.lautturi.com

lautturi.com

output:

Hey!
Created Time:2017-08-29 09:30:26  Author:lautturi