malloc code example

Example 1: malloc in c

#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!"

Example 2: malloc c

int main(int argc, char *argv[])
{
    int* memoireAllouee = NULL;

    memoireAllouee = malloc(sizeof(int));
    if (memoireAllouee == NULL) // Si l'allocation a échoué
    {
        exit(0); // On arrête immédiatement le programme
    }

    // On peut continuer le programme normalement sinon

    return 0;
}

Example 3: Malloc

ptr = malloc(size); //You dont need to cast

Example 4: how to use malloc in c

ptr = (castType*) malloc(size);

Example 5: malloc syntax

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

Example 6: malloc in c

int main(int argc, char *argv[])
{
    int* string = NULL;

    memoireAllouee = malloc(sizeof(int));
    if (string == NULL) 
    {
    	return;
   		string[0] = 'H';
        string[1] = 'e';
        string[2] = 'y';
        string[3] = '!';
        string[4] = '\0';
        printf("%s\n", string);
    }



    return 0;

Tags:

Cpp Example