malloc in c
snippet in c

malloc in c

user8136

//malloc or "memory allocation" reserves a part of the memory

pointer = (cast-type*) malloc(byte-size)
  
//Example
ptr = (int*) malloc(100 * sizeof(int));

Since the size of int is 4 bytes, this statement will allocate 400 bytes
of memory. And, the pointer ptr holds the address of the first byte in
the allocated memory.

malloc in c

user8730

#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);
}

/// output : "Hey!"

allocate memory c

user1869

// Use malloc to allocate memory
ptr = (castType*) malloc(size);
int *exampl = (int*) malloc(sizeof(int));
// Use calloc to allocate and inizialize n contiguous blocks of memory
ptr = (castType*) calloc(n, size);
char *exampl = (char*) calloc(20, sizeof(char));

C malloc

user4038

ptr = (cast-type*)calloc(n, element-size);

malloc in c

user6018

ptr = (cast-type*) malloc(byte-size)

C malloc

user5091

free(ptr);