logo

Dynamisk hukommelsesallokering i C ved hjælp af malloc(), calloc(), free() og realloc()

Da C er et struktureret sprog, har det nogle faste regler for programmering. En af dem omfatter ændring af størrelsen af ​​et array. Et array er en samling af elementer, der er gemt på sammenhængende hukommelsesplaceringer.

arrays



Som det kan ses, er længden (størrelsen) af arrayet ovenfor 9. Men hvad nu hvis der er et krav om at ændre denne længde (størrelse)? For eksempel,

  • Hvis der er en situation, hvor der kun skal indtastes 5 elementer i dette array. I dette tilfælde spilder de resterende 4 indekser bare hukommelse i dette array. Så der er et krav om at mindske længden (størrelsen) af arrayet fra 9 til 5.
  • Tag en anden situation. I denne er der en række af 9 elementer med alle 9 indekser udfyldt. Men der er behov for at indtaste 3 elementer mere i dette array. I dette tilfælde kræves der 3 indeks mere. Så længden (størrelsen) af arrayet skal ændres fra 9 til 12.

Denne procedure kaldes Dynamisk hukommelsestildeling i C .
Derfor har C Dynamisk hukommelsestildeling kan defineres som en procedure, hvor størrelsen af ​​en datastruktur (som Array) ændres under kørsel.
C giver nogle funktioner til at udføre disse opgaver. Der er 4 biblioteksfunktioner leveret af C defineret under header-fil for at lette dynamisk hukommelsesallokering i C-programmering. De er:

  1. malloc()
  2. calloc()
  3. gratis()
  4. realloc()

Lad os se på hver af dem mere detaljeret.



e r model eksempler

C malloc() metode

Det malloc eller hukommelsestildeling metode i C bruges til dynamisk at allokere en enkelt stor blok hukommelse med den angivne størrelse. Det returnerer en pointer af typen void, som kan støbes til en pointer af enhver form. Den initialiserer ikke hukommelsen ved udførelsestidspunktet, så den har initialiseret hver blok med standardaffaldsværdien oprindeligt.

Syntaks for malloc() i C

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

ptr = (int*) malloc(100 * sizeof(int));
Da størrelsen af ​​int er 4 bytes, vil denne sætning tildele 400 bytes hukommelse. Og pointeren ptr holder adressen på den første byte i den allokerede hukommelse.



Hvis pladsen er utilstrækkelig, mislykkes tildelingen og returnerer en NULL-markør.

Eksempel på malloc() i 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; }>

>

linux vært
>

Produktion

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

C calloc() metode

  1. calloc eller sammenhængende tildeling metode i C bruges til dynamisk at allokere det angivne antal hukommelsesblokke af den angivne type. det minder meget om malloc(), men har to forskellige punkter, og disse er:
  2. Den initialiserer hver blok med en standardværdi '0'.
  3. Den har to parametre eller argumenter sammenlignet med malloc().

Syntaks for calloc() i C

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

For eksempel:

ptr = (float*) calloc(25, sizeof(float));
Denne erklæring tildeler sammenhængende plads i hukommelsen til 25 elementer hver med størrelsen af ​​float.

Hvis pladsen er utilstrækkelig, mislykkes tildelingen og returnerer en NULL-markør.

Eksempel på calloc() i 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; }>

>

>

Produktion

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

C free() metode

gratis metode i C bruges til dynamisk de-allokere hukommelsen. Hukommelsen, der er allokeret ved hjælp af funktionerne malloc() og calloc() de-allokeres ikke alene. Derfor bruges free() metoden, når den dynamiske hukommelsesallokering finder sted. Det hjælper med at reducere spild af hukommelse ved at frigøre den.

Syntaks for free() i C

free(ptr);>

Eksempel på free() i 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;> }>

>

>

Produktion

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() metode

realloc eller omfordeling metode i C bruges til dynamisk at ændre hukommelsesallokeringen af ​​en tidligere allokeret hukommelse. Med andre ord, hvis den hukommelse, der tidligere er allokeret ved hjælp af malloc eller calloc, er utilstrækkelig, kan realloc bruges til at dynamisk omalloker hukommelse . genallokering af hukommelse bevarer den allerede nuværende værdi, og nye blokke vil blive initialiseret med standardaffaldsværdien.

Syntaks for realloc() i C

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

Hvis pladsen er utilstrækkelig, mislykkes tildelingen og returnerer en NULL-markør.

Eksempel på realloc() i C

C




maskinsprog
#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; }>

>

>

Produktion

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

Et andet eksempel på realloc()-metoden er:

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;> }>

>

>

java input streng

Produktion: