Динамічний розподіл пам'яті в C за допомогою malloc(), calloc(), free() і realloc()

Динамічний розподіл пам'яті в C за допомогою malloc(), calloc(), free() і realloc()

Оскільки C є структурованою мовою, вона має деякі фіксовані правила програмування. Один із них включає зміну розміру масиву. Масив — це набір елементів, що зберігаються в безперервних місцях пам’яті.

масиви

Як видно, довжина (розмір) масиву вище дорівнює 9. Але що, якщо є вимога змінити цю довжину (розмір)? Наприклад,

  • Якщо виникає ситуація, коли в цей масив потрібно ввести лише 5 елементів. У цьому випадку решта 4 індекси просто витрачають пам’ять у цьому масиві. Отже, існує вимога зменшити довжину (розмір) масиву з 9 до 5.
  • Візьмемо іншу ситуацію. Тут є масив із 9 елементів із заповненими всіма 9 індексами. Але в цей масив потрібно ввести ще 3 елементи. У цьому випадку потрібно ще 3 індекси. Отже, довжину (розмір) масиву потрібно змінити з 9 на 12.

Ця процедура називається Динамічний розподіл пам'яті в C .
Тому C Динамічний розподіл пам'яті можна визначити як процедуру, у якій розмір структури даних (наприклад, масиву) змінюється під час виконання.
C надає деякі функції для досягнення цих завдань. Існує 4 бібліотечні функції, надані C, визначені нижче файл заголовка для полегшення динамічного розподілу пам'яті в програмуванні на C. Вони є:

  1. malloc()
  2. calloc()
  3. безкоштовно()
  4. realloc()

Розглянемо кожен з них докладніше.

C метод malloc().

The malloc або розподіл пам'яті Метод у C використовується для динамічного виділення одного великого блоку пам’яті заданого розміру. Він повертає вказівник типу void, який можна перетворити на вказівник будь-якої форми. Він не ініціалізує пам’ять під час виконання, тому спочатку ініціалізує кожен блок зі значенням сміття за замовчуванням.

Синтаксис malloc() у C

ptr = (cast-type*) malloc(byte-size)   For Example: 

ptr = (int*) malloc(100 * sizeof(int));
Оскільки розмір int становить 4 байти, цей оператор виділить 400 байт пам'яті. І вказівник ptr містить адресу першого байта у виділеній пам’яті.

Якщо місця недостатньо, розподіл не вдається та повертає покажчик NULL.

Приклад malloc() у C

C




#include> #include> int> main()> {> > // This pointer will hold the> > // base address of the block created> > int> * ptr;> > int> n, i;> > // Get the number of elements for the array> > printf> (> 'Enter number of elements:'> );> > scanf> (> '%d'> ,&n);> > printf> (> 'Entered number of elements: %d '> , n);> > // Dynamically allocate memory using malloc()> > ptr = (> int> *)> malloc> (n *> sizeof> (> int> ));> > // Check if the memory has been successfully> > // allocated by malloc or not> > if> (ptr == NULL) {> > printf> (> 'Memory not allocated. '> );> > exit> (0);> > }> > else> {> > // Memory has been successfully allocated> > printf> (> 'Memory successfully allocated using malloc. '> );> > // Get the elements of the array> > for> (i = 0; i ptr[i] = i + 1; } // Print the elements of the array printf('The elements of the array are: '); for (i = 0; i printf('%d, ', ptr[i]); } } return 0; }>

Вихід

Enter number of elements: 5 Memory successfully allocated using malloc. The elements of the array are: 1, 2, 3, 4, 5, 

C метод calloc().

  1. calloc або суміжне виділення Метод у C використовується для динамічного виділення заданої кількості блоків пам'яті зазначеного типу. він дуже схожий на malloc(), але має дві різні точки:
  2. Він ініціалізує кожен блок стандартним значенням «0».
  3. Він має два параметри або аргументи порівняно з malloc().

Синтаксис calloc() у C

ptr = (cast-type*)calloc(n, element-size); here, n is the no. of elements and element-size is the size of each element. 

Наприклад:

ptr = (float*) calloc(25, sizeof(float));
Цей оператор виділяє безперервний простір у пам’яті для 25 елементів, кожен з розміром float.

Якщо місця недостатньо, розподіл не вдається та повертає покажчик NULL.

Приклад calloc() у C

C




#include> #include> int> main()> {> > // This pointer will hold the> > // base address of the block created> > int> * ptr;> > int> n, i;> > // Get the number of elements for the array> > n = 5;> > printf> (> 'Enter number of elements: %d '> , n);> > // Dynamically allocate memory using calloc()> > ptr = (> int> *)> calloc> (n,> sizeof> (> int> ));> > // Check if the memory has been successfully> > // allocated by calloc or not> > if> (ptr == NULL) {> > printf> (> 'Memory not allocated. '> );> > exit> (0);> > }> > else> {> > // Memory has been successfully allocated> > printf> (> 'Memory successfully allocated using calloc. '> );> > // Get the elements of the array> > for> (i = 0; i ptr[i] = i + 1; } // Print the elements of the array printf('The elements of the array are: '); for (i = 0; i printf('%d, ', ptr[i]); } } return 0; }>

Вихід

Enter number of elements: 5 Memory successfully allocated using calloc. The elements of the array are: 1, 2, 3, 4, 5, 

C метод free().

безкоштовно метод у C використовується для динамічного де-розподілити пам'ять. Пам'ять, виділена за допомогою функцій malloc() і calloc(), не вивільняється самостійно. Тому метод free() використовується щоразу, коли відбувається динамічний розподіл пам’яті. Це допомагає зменшити втрату пам’яті, звільняючи її.

Синтаксис free() у C

free(ptr); 

Приклад free() у C

C




#include> #include> int> main()> {> > // This pointer will hold the> > // base address of the block created> > int> *ptr, *ptr1;> > int> n, i;> > // Get the number of elements for the array> > n = 5;> > printf> (> 'Enter number of elements: %d '> , n);> > // Dynamically allocate memory using malloc()> > ptr = (> int> *)> malloc> (n *> sizeof> (> int> ));> > // Dynamically allocate memory using calloc()> > ptr1 = (> int> *)> calloc> (n,> sizeof> (> int> ));> > // Check if the memory has been successfully> > // allocated by malloc or not> > if> (ptr == NULL || ptr1 == NULL) {> > printf> (> 'Memory not allocated. '> );> > exit> (0);> > }> > else> {> > // Memory has been successfully allocated> > printf> (> 'Memory successfully allocated using malloc. '> );> > // Free the memory> > free> (ptr);> > printf> (> 'Malloc Memory successfully freed. '> );> > // Memory has been successfully allocated> > printf> (> ' Memory successfully allocated using calloc. '> );> > // Free the memory> > free> (ptr1);> > printf> (> 'Calloc Memory successfully freed. '> );> > }> > return> 0;> }>

Вихід

Enter number of elements: 5 Memory successfully allocated using malloc. Malloc Memory successfully freed. Memory successfully allocated using calloc. Calloc Memory successfully freed. 

C метод realloc().

перерозподіл або перерозподіл метод у C використовується для динамічної зміни розподілу раніше виділеної пам’яті. Іншими словами, якщо пам'яті, попередньо виділеної за допомогою malloc або calloc, недостатньо, можна використати realloc для динамічно перерозподіляти пам'ять . перерозподіл пам'яті зберігає поточне значення, а нові блоки будуть ініціалізовані стандартним значенням сміття.

Синтаксис realloc() у C

ptr = realloc(ptr, newSize); where ptr is reallocated with new size 'newSize'. 

Якщо місця недостатньо, розподіл не вдається та повертає покажчик NULL.

Приклад realloc() у C

C




#include> #include> int> main()> {> > // This pointer will hold the> > // base address of the block created> > int> * ptr;> > int> n, i;> > // Get the number of elements for the array> > n = 5;> > printf> (> 'Enter number of elements: %d '> , n);> > // Dynamically allocate memory using calloc()> > ptr = (> int> *)> calloc> (n,> sizeof> (> int> ));> > // Check if the memory has been successfully> > // allocated by malloc or not> > if> (ptr == NULL) {> > printf> (> 'Memory not allocated. '> );> > exit> (0);> > }> > else> {> > // Memory has been successfully allocated> > printf> (> 'Memory successfully allocated using calloc. '> );> > // Get the elements of the array> > for> (i = 0; i ptr[i] = i + 1; } // Print the elements of the array printf('The elements of the array are: '); for (i = 0; i printf('%d, ', ptr[i]); } // Get the new size for the array n = 10; printf(' Enter the new size of the array: %d ', n); // Dynamically re-allocate memory using realloc() ptr = (int*)realloc(ptr, n * sizeof(int)); // Memory has been successfully allocated printf('Memory successfully re-allocated using realloc. '); // Get the new elements of the array for (i = 5; i ptr[i] = i + 1; } // Print the elements of the array printf('The elements of the array are: '); for (i = 0; i printf('%d, ', ptr[i]); } free(ptr); } return 0; }>

Вихід

Enter number of elements: 5 Memory successfully allocated using calloc. The elements of the array are: 1, 2, 3, 4, 5, Enter the new size of the array: 10 Memory successfully re-allocated using realloc. The elements of the array are: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 

Ще один приклад методу realloc():

C




#include> #include> int> main()> {> > int> index = 0, i = 0, n,> > *marks;> // this marks pointer hold the base address> > // of the block created> > int> ans;> > marks = (> int> *)> malloc> (> sizeof> (> > int> ));> // dynamically allocate memory using malloc> > // check if the memory is successfully allocated by> > // malloc or not?> > if> (marks == NULL) {> > printf> (> 'memory cannot be allocated'> );> > }> > else> {> > // memory has successfully allocated> > printf> (> 'Memory has been successfully allocated by '> > 'using malloc '> );> > printf> (> ' marks = %pc '> ,> > marks);> // print the base or beginning> > // address of allocated memory> > do> {> > printf> (> ' Enter Marks '> );> > scanf> (> '%d'> , &marks[index]);> // Get the marks> > printf> (> 'would you like to add more(1/0): '> );> > scanf> (> '%d'> , &ans);> > if> (ans == 1) {> > index++;> > marks = (> int> *)> realloc> (> > marks,> > (index + 1)> > *> sizeof> (> > int> ));> // Dynamically reallocate> > // memory by using realloc> > // check if the memory is successfully> > // allocated by realloc or not?> > if> (marks == NULL) {> > printf> (> 'memory cannot be allocated'> );> > }> > else> {> > printf> (> 'Memory has been successfully '> > 'reallocated using realloc: '> );> > printf> (> > ' base address of marks are:%pc'> ,> > marks);> ////print the base or> > ///beginning address of> > ///allocated memory> > }> > }> > }> while> (ans == 1);> > // print the marks of the students> > for> (i = 0; i <= index; i++) {> > printf> (> 'marks of students %d are: %d '> , i,> > marks[i]);> > }> > free> (marks);> > }> > return> 0;> }>

Вихід: