logo

Dynamická alokace paměti v C pomocí malloc(), calloc(), free() a realloc()

Protože C je strukturovaný jazyk, má určitá pevná pravidla pro programování. Jedním z nich je změna velikosti pole. Pole je kolekce položek uložených v souvislých paměťových místech.

pole



Jak je vidět, délka (velikost) pole výše je 9. Ale co když existuje požadavek na změnu této délky (velikost)? Například,

  • Pokud nastane situace, kdy je potřeba do tohoto pole zadat pouze 5 prvků. V tomto případě zbývající 4 indexy pouze plýtvají pamětí v tomto poli. Existuje tedy požadavek zmenšit délku (velikost) pole z 9 na 5.
  • Vezměte si jinou situaci. V tomto je pole 9 prvků s vyplněnými všemi 9 indexy. Do tohoto pole je ale potřeba zadat další 3 prvky. V tomto případě jsou vyžadovány 3 indexy navíc. Takže délku (velikost) pole je třeba změnit z 9 na 12.

Tento postup se označuje jako Dynamická alokace paměti v C .
Proto C Dynamická alokace paměti lze definovat jako proceduru, ve které se během běhu mění velikost datové struktury (jako Array).
C poskytuje některé funkce k dosažení těchto úkolů. Existují 4 knihovní funkce poskytované jazykem C definované pod hlavičkový soubor pro usnadnění dynamické alokace paměti v programování C. Oni jsou:

  1. malloc()
  2. calloc()
  3. volný, uvolnit()
  4. realloc()

Podívejme se na každou z nich podrobněji.



C malloc() metoda

The malloc nebo alokace paměti metoda v C se používá k dynamickému přidělování jednoho velkého bloku paměti o zadané velikosti. Vrací ukazatel typu void, který lze přetypovat na ukazatel libovolného tvaru. Neinicializuje paměť v době provádění, takže zpočátku inicializovala každý blok s výchozí hodnotou nesmyslu.

Syntaxe malloc() v C

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

ptr = (int*) malloc(100 * sizeof(int));
Protože velikost int je 4 bajty, tento příkaz přidělí 400 bajtů paměti. A ukazatel ptr obsahuje adresu prvního bytu v přidělené paměti.



Pokud není dostatek místa, přidělení se nezdaří a vrátí ukazatel NULL.

Příklad malloc() v C

C




vlc ke stažení z youtube

#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ýstup

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

C metoda calloc().

  1. calloc nebo souvislá alokace metoda v C se používá k dynamickému přidělování zadaného počtu bloků paměti zadaného typu. je velmi podobný malloc(), ale má dva různé body a tyto jsou:
  2. Inicializuje každý blok s výchozí hodnotou „0“.
  3. Má dva parametry nebo argumenty ve srovnání s malloc().

Syntaxe 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.>

Například:

ptr = (float*) calloc(25, sizeof(float));
Tento příkaz alokuje souvislý prostor v paměti pro 25 prvků, z nichž každý má velikost plováku.

Pokud není dostatek místa, přidělení se nezdaří a vrátí ukazatel NULL.

Pří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ýstup

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

C free() metoda

volný, uvolnit metoda v C se používá k dynamicky de-alokovat vzpomínka. Paměť alokovaná pomocí funkcí malloc() a calloc() není sama o sobě alokována. Proto se metoda free() používá vždy, když dochází k dynamické alokaci paměti. Pomáhá snižovat plýtvání pamětí tím, že ji uvolňuje.

Syntaxe free() v C

free(ptr);>

Příklad free() v C

C


Rozvržení mřížky



#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ýstup

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

C metoda realloc().

realloc nebo přerozdělení metoda v C se používá k dynamické změně alokace paměti dříve přidělené paměti. Jinými slovy, pokud paměť dříve přidělená pomocí malloc nebo calloc nestačí, lze použít realloc dynamicky znovu alokovat paměť . opětovné přidělení paměti zachová již současnou hodnotu a nové bloky budou inicializovány s výchozí hodnotou nesmyslu.

Syntaxe realloc() v C

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

Pokud není dostatek místa, přidělení se nezdaří a vrátí ukazatel NULL.

Pří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ýstup

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,>

Dalším příkladem metody 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ýstup: