Dynamic memory: malloc, free, and realloc · Memória dinâmica: malloc, free e realloc
Stack memory vs heap memory
- Normal local variables live on the stack. They appear when a function starts and vanish when it returns.
- Sometimes you need memory that outlives the function, or whose size you only know at run time.
- That memory comes from the heap. You ask for it, and later you give it back.
Memória de pilha vs memória de heap
- Variáveis locais normais vivem na pilha. Elas aparecem quando uma função começa e desaparecem quando ela retorna.
- Às vezes você precisa de memória que sobreviva à função, ou cujo tamanho só sabe em tempo de execução.
- Essa memória vem do heap. Você pede por ela, e depois a devolve.
malloc and sizeof
mallocasks the heap for a block of bytes and returns a pointer to it.- Use
sizeofto get the size of one item:malloc(n * sizeof(int))makes room fornints. - The block is yours to use through the pointer, exactly like an array:
a[0],a[1], ...
malloc e sizeof
mallocpede ao heap um bloco de bytes e retorna um ponteiro para ele.- Use
sizeofpara obter o tamanho de um item:malloc(n * sizeof(int))faz espaço paranints. - O bloco é seu para usar através do ponteiro, exatamente como um array:
a[0],a[1], ...
free and memory leaks
- When you are done with heap memory, give it back with
free(pointer). - If you never
freeit, the program leaks memory — it holds space it no longer uses. - Rule for these tasks: your function allocates and returns; the checker frees it. Do not call
freeyourself.
free e vazamentos de memória
- Quando terminar com memória heap, devolva-a com
free(pointer). - Se nunca
free, o programa vaza memória — ele mantém espaço que não usa mais. - Regra para estas tarefas: sua função aloca e retorna; o checker libera. Não chame
freesozinho.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int *a = malloc(3 * sizeof(int)); // room for 3 ints
a[0] = 5; a[1] = 6; a[2] = 7;
printf("%d\n", a[0] + a[1] + a[2]); // 18
free(a); // give it back
return 0;
}
Growing an array with realloc
realloc(a, newSize)resizes a heap block, keeping the old contents.- It may move the block, so always use its return value:
a = realloc(a, ...). - This is how you grow an array one item at a time, like a list that gets longer.
Crescendo um array com realloc
realloc(a, newSize)redimensiona um bloco heap, mantendo o conteúdo antigo.- Ele pode mover o bloco, então sempre use seu valor de retorno:
a = realloc(a, ...). - É assim que você cresce um array item por item, como uma lista que fica maior.
Common mistakes
- Every
mallocneeds a matchingfree; do not use memory afterfree. - Check that
mallocdid not returnNULL.
Erros comuns
- Todo
mallocprecisa de um correspondentefree; não use memória apósfree. - Verifique se
mallocnão retornouNULL.
Now you try
- Use
malloc(n * sizeof(int))for new arrays, and#include <stdlib.h>. - Your function returns the pointer; the checker frees it — do not call
free. Do not write amain.
Agora você tenta
- Use
malloc(n * sizeof(int))para novos arrays, e#include <stdlib.h>. - Sua função retorna o ponteiro; o checker o libera — não chame
free. Não escreva ummain.
Complete int *make_array(int n, int value) so it allocates n ints (with malloc), sets every one to value, and returns the pointer. The checker frees it. Do not · não write a main. · Complete int *make_array(int n, int value) para alocar n ints (com malloc), defina cada um como value, e retorne o ponteiro. O verificador faz free dele. Não escreva um main.
Click Run to see the output here. · Clique em Executar para ver a saída aqui.
Complete int *concat(const int a[], int na, const int b[], int nb) so it allocates na + nb ints, copies all of a then all of b, and returns the pointer. The checker frees it. Do not · não write a main. · Complete int *concat(const int a[], int na, const int b[], int nb) para alocar na + nb ints, copie tudo de a depois tudo de b, e retorne o ponteiro. O verificador faz free dele. Não escreva um main.
Click Run to see the output here. · Clique em Executar para ver a saída aqui.
Complete int *push(int *a, int *len, int value) so it grows the heap array a to hold one more int with realloc, stores value at the end, increases *len by 1, and returns the new pointer. The checker frees it. Do not · não write a main. · Complete int *push(int *a, int *len, int value) para que ele cresça o array do heap a para armazenar mais um int com realloc, armazene value no final, aumente *len em 1 e retorne o novo ponteiro. O verificador libera a memória. Não escreva um main.
Click Run to see the output here. · Clique em Executar para ver a saída aqui.