Introducing
During the development of the C (or C+) language we will one day need to use the malloc
, but when? Suppose, you create a program to receive personal data and in a part need to enter your name.
For example:
#include <stdio.h>
#include <stdlib.h>
char nome[80]; //amazena nome
int main()
{
printf("Insira seu nome: ");
scanf("%s", nome);
printf("\n\nNome: %s", nome);
return 0;
}
//Saída
//Insira seu nome: Algum nome
//Nome: Algum
The example above shows the name entry, if I put my name: John Paul, will only leave John because in the Array of char
would have the name space as João\0Paulo
. If it were used:
#include <stdio.h>
#include <stdlib.h>
char nome[80];
int main()
{
printf("Insira seu nome: ");
gets(nome); //Apenas é um exemplo usando gets mas não use muito pode causar o estouro do buffer.
printf("\n\nNome: %s", nome);
return 0;
}
//Saída
//Insira seu nome: Algum nome
//Nome: Algum nome
In this part we have the whole name being displayed. But what happens? In the array of char
there are still spaces in the positions that were allocated in memory, what these unused spaces would be having a waste. To solve this we can use the malloc
.
Use of the malloc
The malloc
makes "Dynamic Memory Allocation", that is, allocates in memory a part to be used if in the above example nome
would not be wasted.
void* malloc (size_t size);
Like the malloc
has the return void
we should make a Typecast to convert void
in char
. See below:
#include <stdio.h>
#include <stdlib.h>
char* nome; //note que agora o nome é um ponteiro.
int main()
{
nome = (char*) malloc(sizeof(char) + 1);
//podemos usar o sizeof para receber o tamanho de char e acrescentar +1 para ter um tamanho recomendado
printf("Insira seu nome: ");
gets(nome);
printf("\n\nNome: %s", nome);
free(nome);
return 0;
}
//Saída
//Insira seu nome: Algum nome
//Nome: Algum nome
At the end note that we have free
in the end, it is used to free the allocated memory, when no longer need the variable, use the free
to leave the memory free. That’s why I recommend the malloc
.
References
malloc
C++ Reference
free
C++ Reference
Did the answer solve your question? Do you think you can accept it? See [tour] if you don’t know how you do it. This would help a lot to indicate that the solution was useful to you. You can also vote on any question or answer you find useful on the entire site.
– Maniero