1#include <stdlib.h>
2
3void *malloc(size_t size);
4
5void exemple(void)
6{
7 char *string;
8
9 string = malloc(sizeof(char) * 5);
10 if (string == NULL)
11 return;
12 string[0] = 'H';
13 string[1] = 'e';
14 string[2] = 'y';
15 string[3] = '!';
16 string[4] = '\0';
17 printf("%s\n", string);
18 free(string);
19}
20
21/// output : "Hey!"
1int main(int argc, char *argv[])
2{
3 int* memoireAllouee = NULL;
4
5 memoireAllouee = malloc(sizeof(int));
6 if (memoireAllouee == NULL) // Si l'allocation a échoué
7 {
8 exit(0); // On arrête immédiatement le programme
9 }
10
11 // On peut continuer le programme normalement sinon
12
13 return 0;
14}
15
1// Let's allocate enough space on the heap for an array storing 4 ints
2
3intArray = (int *) malloc(4 * sizeof(int)); // A pointer to an array of ints
4
5intArray[0] = 10;
6intArray[1] = 20;
7intArray[2] = 25;
8intArray[3] = 35;
1#include <stdlib.h>
2int main(){
3int *ptr;
4ptr = malloc(15 * sizeof(*ptr)); /* a block of 15 integers */
5 if (ptr != NULL) {
6 *(ptr + 5) = 480; /* assign 480 to sixth integer */
7 printf("Value of the 6th integer is %d",*(ptr + 5));
8 }
9}