Dynamická alokácia pamäte v C pomocou malloc(), calloc(), free() a realloc()
Keďže C je štruktúrovaný jazyk, má určité pevné pravidlá pre programovanie. Jedným z nich je zmena veľkosti poľa. Pole je kolekcia položiek uložených v súvislých pamäťových miestach.
Ako je možné vidieť, dĺžka (veľkosť) poľa vyššie je 9. Čo ak však existuje požiadavka na zmenu tejto dĺžky (veľkosti)? Napríklad,
- Ak nastane situácia, že do tohto poľa je potrebné zadať iba 5 prvkov. V tomto prípade zostávajúce 4 indexy len plytvajú pamäťou v tomto poli. Existuje teda požiadavka zmenšiť dĺžku (veľkosť) poľa z 9 na 5.
- Vezmite si inú situáciu. V tomto je pole 9 prvkov so všetkými 9 vyplnenými indexmi. Do tohto poľa je však potrebné zadať ďalšie 3 prvky. V tomto prípade sú potrebné 3 indexy navyše. Takže dĺžku (veľkosť) poľa je potrebné zmeniť z 9 na 12.
Tento postup sa označuje ako Dynamická alokácia pamäte v C .
Preto C Dynamická alokácia pamäte možno definovať ako procedúru, v ktorej sa počas behu mení veľkosť dátovej štruktúry (ako Array).
C poskytuje niektoré funkcie na dosiahnutie týchto úloh. K dispozícii sú 4 knižničné funkcie poskytované jazykom C definované pod hlavičkový súbor na uľahčenie dynamickej alokácie pamäte v programovaní C. Oni sú:
- malloc()
- calloc()
- zadarmo()
- realloc()
Pozrime sa na každú z nich podrobnejšie.
C malloc() metóda
The malloc alebo alokácia pamäte metóda v C sa používa na dynamickú alokáciu jedného veľkého bloku pamäte so špecifikovanou veľkosťou. Vracia ukazovateľ typu void, ktorý možno prehodiť do ukazovateľa ľubovoľnej formy. Neinicializuje pamäť v čase vykonávania, takže na začiatku inicializoval každý blok s predvolenou hodnotou odpadu.
Syntax malloc() v C
ptr = (cast-type*) malloc(byte-size) For Example:
ptr = (int*) malloc(100 * sizeof(int));
Keďže veľkosť int je 4 bajty, tento príkaz pridelí 400 bajtov pamäte. A ukazovateľ ptr obsahuje adresu prvého bajtu v pridelenej pamäti.
Ak je miesto nedostatočné, pridelenie zlyhá a vráti ukazovateľ NULL.
Príklad malloc() v 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; }> |
Výkon
Enter number of elements: 5 Memory successfully allocated using malloc. The elements of the array are: 1, 2, 3, 4, 5,
C metóda calloc().
- calloc alebo súvislá alokácia metóda v C sa používa na dynamickú alokáciu určeného počtu blokov pamäte určeného typu. je veľmi podobný malloc(), ale má dva rôzne body a tieto sú:
- Inicializuje každý blok s predvolenou hodnotou „0“.
- V porovnaní s malloc() má dva parametre alebo argumenty.
Syntax calloc() v C
ptr = (cast-type*)calloc(n, element-size); here, n is the no. of elements and element-size is the size of each element.
Napríklad:
ptr = (float*) calloc(25, sizeof(float));
Tento príkaz prideľuje súvislý priestor v pamäti pre 25 prvkov, z ktorých každý má veľkosť plaváka.
Ak je miesto nedostatočné, pridelenie zlyhá a vráti ukazovateľ NULL.
Príklad calloc() v 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; }> |
Výkon
Enter number of elements: 5 Memory successfully allocated using calloc. The elements of the array are: 1, 2, 3, 4, 5,
C free() metóda
zadarmo metóda v C sa používa na dynamicky de-alokovať pamäť. Pamäť alokovaná pomocou funkcií malloc() a calloc() nie je sama osebe alokovaná. Preto sa metóda free() používa vždy, keď sa uskutoční dynamická alokácia pamäte. Pomáha znižovať plytvanie pamäťou tým, že ju uvoľňuje.
Syntax free() v C
free(ptr);
Príklad free() v 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;> }> |
Výkon
Enter number of elements: 5 Memory successfully allocated using malloc. Malloc Memory successfully freed. Memory successfully allocated using calloc. Calloc Memory successfully freed.
C metóda realloc().
realloc alebo prerozdelenie metóda v C sa používa na dynamickú zmenu alokácie pamäte predtým pridelenej pamäte. Inými slovami, ak pamäť predtým pridelená pomocou malloc alebo calloc je nedostatočná, možno použiť realloc dynamicky prerozdeľovať pamäť . opätovné pridelenie pamäte zachová už súčasnú hodnotu a nové bloky budú inicializované s predvolenou hodnotou odpadu.
Syntax realloc() v C
ptr = realloc(ptr, newSize); where ptr is reallocated with new size 'newSize'.
Ak je miesto nedostatočné, pridelenie zlyhá a vráti ukazovateľ NULL.
Príklad realloc() v 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; }> |
Výkon
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,
Ďalším príkladom metódy realloc() je:
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;> }> |
Výkon: