logo

Dynaaminen muistin varaus C:ssä käyttämällä malloc(), calloc(), free() ja realloc()

Koska C on strukturoitu kieli, sillä on joitain kiinteitä ohjelmointisääntöjä. Yksi niistä sisältää taulukon koon muuttamisen. Joukko on kokoelma vierekkäisiin muistipaikkoihin tallennettuja kohteita.

taulukoita



Kuten voidaan nähdä, yllä olevan taulukon pituus (koko) on 9. Mutta entä jos tätä pituutta (kokoa) on muutettava? Esimerkiksi,

tulostaa javasta
  • Jos on tilanne, jossa tähän taulukkoon tarvitaan vain 5 elementtiä. Tässä tapauksessa loput 4 indeksiä vain tuhlaavat muistia tässä taulukossa. Joten taulukon pituutta (kokoa) on pienennettävä 9:stä 5:een.
  • Ota toinen tilanne. Tässä on 9 elementin joukko, joissa kaikki 9 indeksiä on täytetty. Mutta tähän taulukkoon on syötettävä vielä 3 elementtiä. Tässä tapauksessa tarvitaan 3 indeksiä lisää. Joten taulukon pituus (koko) on muutettava arvosta 9 arvoon 12.

Tätä menettelyä kutsutaan nimellä Dynaaminen muistin varaus C-muodossa .
Siksi C Dynaaminen muistin varaus voidaan määritellä proseduuriksi, jossa tietorakenteen (kuten Array) kokoa muutetaan ajon aikana.
C tarjoaa joitain toimintoja näiden tehtävien suorittamiseksi. C:llä on 4 kirjastotoimintoa, jotka on määritelty alla otsikkotiedosto helpottaa dynaamista muistin varaamista C-ohjelmoinnissa. He ovat:

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

Katsotaanpa kutakin niistä yksityiskohtaisemmin.



C malloc() -menetelmä

The malloc tai muistin varaus C:n menetelmää käytetään yhden suuren muistilohkon dynaamiseen varaamiseen määritetyn kokoisella muistilla. Se palauttaa void-tyypin osoittimen, joka voidaan heittää minkä tahansa muotoiseksi osoittimeksi. Se ei alusta muistia suoritushetkellä, joten se on alustanut jokaisen lohkon alun perin oletusarvolla.

Malloc():n syntaksi C:ssä

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

ptr = (int*) malloc(100 * sizeof(int));
Koska int:n koko on 4 tavua, tämä lauseke varaa 400 tavua muistia. Ja osoitin ptr pitää ensimmäisen tavun osoitteen varatussa muistissa.



Jos tila ei riitä, varaus epäonnistuu ja palauttaa NULL-osoittimen.

Esimerkki malloc():sta C:ssä

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

>

>

Lähtö

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

C calloc() -menetelmä

  1. calloc tai vierekkäinen jako C:n menetelmää käytetään dynaamisesti allokoimaan määritetty määrä tietyn tyyppisiä muistilohkoja. se on hyvin samanlainen kuin malloc(), mutta siinä on kaksi eri pistettä ja nämä ovat:
  2. Se alustaa jokaisen lohkon oletusarvolla '0'.
  3. Siinä on kaksi parametria tai argumenttia verrattaessa malloc(:iin).

Calloc():n syntaksi C:ssä

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

Esimerkiksi:

ptr = (kelluke*) calloc(25, koko(kelluke));
Tämä lauseke varaa muistissa vierekkäistä tilaa 25 elementille kukin kelluntakoon mukaan.

Jos tila ei riitä, varaus epäonnistuu ja palauttaa NULL-osoittimen.

Esimerkki calloc():sta C:ssä

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

>

>

Lähtö

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

C free() -menetelmä

vapaa menetelmää C:ssä käytetään dynaamisesti purkaa muisti. Funktioilla malloc() ja calloc() varattua muistia ei pureta yksinään. Tästä syystä free()-menetelmää käytetään aina, kun dynaaminen muistin varaus tapahtuu. Se auttaa vähentämään muistin tuhlausta vapauttamalla sitä.

Free()-syntaksi C:ssä

free(ptr);>

Esimerkki free():stä C:ssä

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

>

nbsp
>

Lähtö

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() -menetelmä

realloc tai uudelleenjako C:n menetelmää käytetään dynaamisesti muuttamaan aiemmin varatun muistin muistin varausta. Toisin sanoen, jos aiemmin mallocin tai callocin avulla varattu muisti ei riitä, voidaan reallocilla varaa muistia dynaamisesti uudelleen . muistin uudelleenallokointi säilyttää jo nykyisen arvon ja uudet lohkot alustetaan oletusarvolla.

Realloc():n syntaksi C:ssä

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

Jos tila ei riitä, varaus epäonnistuu ja palauttaa NULL-osoittimen.

Esimerkki realloc():sta C:ssä

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

>

>

Lähtö

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

Toinen esimerkki realloc()-menetelmästä on:

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

mikä on build-essential ubuntu

>

>

Lähtö: