1#include <iostream>
2#include <cstdlib>
3using namespace std;
4
5int main()
6{
7 int *ptr;
8 ptr = (int*) malloc(5*sizeof(int));
9
10 if(!ptr)
11 {
12 cout << "Memory Allocation Failed";
13 exit(1);
14 }
15 cout << "Initializing values..." << endl << endl;
16
17 for (int i=0; i<5; i++)
18 {
19 ptr[i] = i*2+1;
20 }
21 cout << "Initialized values" << endl;
22
23 for (int i=0; i<5; i++)
24 {
25 /* ptr[i] and *(ptr+i) can be used interchangeably */
26 cout << *(ptr+i) << endl;
27 }
28
29 free(ptr);
30 return 0;
31}
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