1// Use malloc to allocate memory
2ptr = (castType*) malloc(size);
3int *exampl = (int*) malloc(sizeof(int));
4// Use calloc to allocate and inizialize n contiguous blocks of memory
5ptr = (castType*) calloc(n, size);
6char *exampl = (char*) calloc(20, sizeof(char));
1/* malloc example: random string generator*/
2#include <stdio.h> /* printf, scanf, NULL */
3#include <stdlib.h> /* malloc, free, rand */
4
5int main ()
6{
7 int i,n;
8 char * buffer;
9
10 printf ("How long do you want the string? ");
11 scanf ("%d", &i);
12
13 buffer = (char*) malloc (i+1);
14 if (buffer==NULL) exit (1);
15
16 for (n=0; n<i; n++)
17 buffer[n]=rand()%26+'a';
18 buffer[i]='\0';
19
20 printf ("Random string: %s\n",buffer);
21 free (buffer);
22
23 return 0;
24}
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;
1int main(int argc, char *argv[])
2{
3 int* string = NULL;
4
5 memoireAllouee = malloc(sizeof(int));
6 if (string == NULL)
7 {
8 return;
9 string[0] = 'H';
10 string[1] = 'e';
11 string[2] = 'y';
12 string[3] = '!';
13 string[4] = '\0';
14 printf("%s\n", string);
15 }
16
17
18
19 return 0;