logo

Allocazione dinamica della memoria in C utilizzando malloc(), calloc(), free() e realloc()

Poiché il C è un linguaggio strutturato, ha alcune regole fisse per la programmazione. Uno di questi include la modifica della dimensione di un array. Un array è una raccolta di elementi archiviati in posizioni di memoria contigue.

matrici



Come si può vedere, la lunghezza (dimensione) dell'array sopra è 9. Ma cosa succede se è necessario modificare questa lunghezza (dimensione)? Per esempio,

  • Se esiste una situazione in cui è necessario inserire solo 5 elementi in questo array. In questo caso, i restanti 4 indici stanno solo sprecando memoria in questo array. Quindi è necessario ridurre la lunghezza (dimensione) dell'array da 9 a 5.
  • Prendi un'altra situazione. In questo c'è un array di 9 elementi con tutti e 9 gli indici riempiti. Ma è necessario inserire altri 3 elementi in questo array. In questo caso sono necessari 3 indici in più. Pertanto la lunghezza (dimensione) dell'array deve essere modificata da 9 a 12.

Questa procedura è denominata Allocazione dinamica della memoria in C .
Pertanto, C Allocazione dinamica della memoria può essere definito come una procedura in cui la dimensione di una struttura dati (come Array) viene modificata durante il runtime.
C fornisce alcune funzioni per realizzare questi compiti. Ci sono 4 funzioni di libreria fornite da C definite sotto file di intestazione per facilitare l'allocazione dinamica della memoria nella programmazione C. Sono:

  1. malloc()
  2. calloc()
  3. gratuito()
  4. rialloc()

Diamo un'occhiata a ciascuno di essi in modo più dettagliato.



Metodo C malloc()

IL malloc O allocazione della memoria Il metodo in C viene utilizzato per allocare dinamicamente un singolo grande blocco di memoria con la dimensione specificata. Restituisce un puntatore di tipo void che può essere trasformato in un puntatore di qualsiasi forma. Non inizializza la memoria in fase di esecuzione in modo che inizialmente abbia inizializzato ciascun blocco con il valore spazzatura predefinito.

Sintassi di malloc() in C

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

ptr = (int*) malloc(100 * sizeof(int));
Poiché la dimensione di int è 4 byte, questa istruzione allocherà 400 byte di memoria. Inoltre, il puntatore ptr contiene l'indirizzo del primo byte nella memoria allocata.



Se lo spazio è insufficiente, l'allocazione fallisce e restituisce un puntatore NULL.

Esempio di malloc() in C

C

ricerca binaria




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

>

>

Produzione

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

Metodo C calloc()

  1. calloc O allocazione contigua Il metodo in C viene utilizzato per allocare dinamicamente il numero specificato di blocchi di memoria del tipo specificato. è molto simile a malloc() ma ha due punti diversi e questi sono:
  2. Inizializza ciascun blocco con un valore predefinito '0'.
  3. Ha due parametri o argomenti rispetto a malloc().

Sintassi di calloc() in C

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

Per esempio:

ptr = (float*) calloc(25, sizeof(float));
Questa istruzione alloca spazio contiguo in memoria per 25 elementi ciascuno con la dimensione del float.

algoritmo rr

Se lo spazio è insufficiente, l'allocazione fallisce e restituisce un puntatore NULL.

Esempio di calloc() in 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; }>

>

>

Produzione

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

Metodo C gratuito()

gratuito Il metodo in C viene utilizzato in modo dinamico deallocare la memoria. La memoria allocata utilizzando le funzioni malloc() e calloc() non viene deallocata da sola. Pertanto viene utilizzato il metodo free() ogni volta che avviene l'allocazione dinamica della memoria. Aiuta a ridurre lo spreco di memoria liberandola.

Sintassi di free() in C

free(ptr);>

Esempio di free() in 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;> }>

>

>

Produzione

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

Metodo C realloc()

rialloc O riallocazione Il metodo in C viene utilizzato per modificare dinamicamente l'allocazione di memoria di una memoria precedentemente allocata. In altre parole, se la memoria precedentemente allocata con l'aiuto di malloc o calloc è insufficiente, è possibile utilizzare realloc per riallocare dinamicamente la memoria . la riallocazione della memoria mantiene il valore già presente e i nuovi blocchi verranno inizializzati con il valore spazzatura predefinito.

Sintassi di realloc() in C

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

Se lo spazio è insufficiente, l'allocazione fallisce e restituisce un puntatore NULL.

Esempio di realloc() in C

C




bash se condizione
#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; }>

>

>

Produzione

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

Un altro esempio per il metodo 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;> }>

>

>

convertire la stringa in json in Java

Produzione: