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}
1int alloc_size = 10;
2int* buffer = (int*) malloc (alloc_size);
3//Allocate memory block which can fit 10 integers