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 *p = new int; // request memory
2*p = 5; // store value
3
4cout << *p << endl; // Output is 5
5
6delete p; // free up the memory
7
8cout << *p << endl; // Output is 0
1char* pvalue = NULL; // Pointer initialized with null
2pvalue = new char[20]; // Request memory for the variable
3
1#include <iostream>
2using namespace std;
3
4int main () {
5 double* pvalue = NULL; // Pointer initialized with null
6 pvalue = new double; // Request memory for the variable
7
8 *pvalue = 29494.99; // Store value at allocated address
9 cout << "Value of pvalue : " << *pvalue << endl;
10
11 delete pvalue; // free up the memory.
12
13 return 0;
14}
1C Dynamic Memory Allocation can be defined as a procedure in which the size of a data structure (like Array) is changed during the runtime.
2C provides some functions to achieve these tasks. There are 4 library functions provided by C defined under <stdlib.h> header file to facilitate dynamic memory allocation in C programming. They are:
3
4
5malloc()
6calloc()
7free()
8realloc()