When to actually use malloc() and/or calloc()?

Asked

Viewed 267 times

1

My doubt is due to the fact that I am learning from banal examples (in my view), as in: int *ptr; ptr = malloc(sizeof(int));

It seems to me useless to allocate a space of an integer to a pointer of the whole type, it no longer does it alone?

When do I actually use these dynamic memory allocation functions? If you could give examples, it would be of great value.

  • 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.

2 answers

1

I could have done it that’s easier, right?

int *ptr = malloc(sizeof(int));

I put in the Github for future reference.

So it seems to me that the biggest problem is to be making codes without really understanding what is happening there.

We can’t say without a bigger context if that’s really necessary. It’s even possible for a very basic exercise just to show the malloc() in action makes some sense, but for use in real application it really shouldn’t be used in most cases.

Is there any reason to allocate the integer in heap? It is unlikely. Its size is small, and if the data survives the lifetime of the function it is created the easiest is to return this value or return through a parameter by reference, but not to allocate dynamically. Allocate with malloc() will force you under normal conditions to give a free(), Whoever receives this amount must fulfill the release contract. It does not compensate for something so simple.

Examples of cases and reasons to use these functions have already been answered:

0

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.