logo

Asignación de memoria dinámica en C usando malloc(), calloc(), free() y realloc()

Dado que C es un lenguaje estructurado, tiene algunas reglas fijas de programación. Uno de ellos incluye cambiar el tamaño de una matriz. Una matriz es una colección de elementos almacenados en ubicaciones de memoria contiguas.

matrices

Como puede verse, la longitud (tamaño) de la matriz anterior es 9. Pero, ¿qué pasa si es necesario cambiar esta longitud (tamaño)? Por ejemplo,



bloquear anuncios de youtube en android
  • Si hay una situación en la que solo se necesitan ingresar 5 elementos en esta matriz. En este caso, los 4 índices restantes simplemente están desperdiciando memoria en esta matriz. Por lo tanto, es necesario reducir la longitud (tamaño) de la matriz de 9 a 5.
  • Tomemos otra situación. En esto, hay una matriz de 9 elementos con los 9 índices llenos. Pero es necesario ingresar 3 elementos más en esta matriz. En este caso, se requieren 3 índices más. Por lo tanto, es necesario cambiar la longitud (tamaño) de la matriz de 9 a 12.

Este procedimiento se conoce como Asignación de memoria dinámica en C .
Por lo tanto, C Asignación de memoria dinámica se puede definir como un procedimiento en el que el tamaño de una estructura de datos (como una matriz) se cambia durante el tiempo de ejecución.
C proporciona algunas funciones para lograr estas tareas. Hay 4 funciones de biblioteca proporcionadas por C definidas en Archivo de encabezado para facilitar la asignación de memoria dinámica en la programación C. Ellos son:

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

Veamos cada uno de ellos con mayor detalle.

Método C malloc()

El malloc o asignación de memoria El método en C se utiliza para asignar dinámicamente un único bloque grande de memoria con el tamaño especificado. Devuelve un puntero de tipo void que se puede convertir en un puntero de cualquier forma. No inicializa la memoria en el momento de la ejecución, por lo que inicialmente ha inicializado cada bloque con el valor basura predeterminado.

Sintaxis de malloc() en C

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

ptr = (int*) malloc(100 * tamaño de(int));
Dado que el tamaño de int es de 4 bytes, esta declaración asignará 400 bytes de memoria. Y el puntero ptr contiene la dirección del primer byte en la memoria asignada.

Si el espacio es insuficiente, la asignación falla y devuelve un puntero NULL.

Ejemplo de malloc() en 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; }>

>

>

Producción

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

Método C calloc()

  1. calloc o asignación contigua El método en C se utiliza para asignar dinámicamente el número especificado de bloques de memoria del tipo especificado. es muy similar a malloc() pero tiene dos puntos diferentes y estos son:
  2. Inicializa cada bloque con un valor predeterminado '0'.
  3. Tiene dos parámetros o argumentos en comparación con malloc().

Sintaxis de calloc() en C

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

Por ejemplo:

ptr = (flotante*) calloc(25, tamaño de(flotante));
Esta declaración asigna espacio contiguo en la memoria para 25 elementos, cada uno con el tamaño del flotador.

Si el espacio es insuficiente, la asignación falla y devuelve un puntero NULL.

Ejemplo de calloc() en 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; }>

>

>

Producción

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

Método C libre()

gratis El método en C se utiliza para dinámicamente de-allocate la memoria. La memoria asignada mediante las funciones malloc() y calloc() no se desasigna por sí sola. Por lo tanto, se utiliza el método free() siempre que se realiza la asignación de memoria dinámica. Ayuda a reducir el desperdicio de memoria liberándola.

Sintaxis de free() en C

free(ptr);>

Ejemplo de gratis() en 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;> }>

>

dormir en javascript
>

Producción

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

Método C realloc()

reasignar o reasignación El método en C se utiliza para cambiar dinámicamente la asignación de memoria de una memoria previamente asignada. En otras palabras, si la memoria previamente asignada con la ayuda de malloc o calloc es insuficiente, se puede utilizar realloc para reasignar memoria dinámicamente . La reasignación de memoria mantiene el valor ya presente y los nuevos bloques se inicializarán con el valor basura predeterminado.

Sintaxis de realloc() en C

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

Si el espacio es insuficiente, la asignación falla y devuelve un puntero NULL.

Ejemplo de realloc() en 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; }>

>

>

Producción

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

Otro ejemplo del método realloc() es:

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

cómo descargar música

>

>

Producción: