Dynamic memory: malloc, calloc, realloc and free
So far the size of your data was decided when writing the program: an array of 10 elements has 10, always. But often you only know how much you need while the program runs, for example when the user says how many items they will enter. Dynamic memory solves this: you request a block of the size you want at run time and, when you finish, you give it back. It lives in an area called the heap, different from the stack where local variables go.
malloc and free
malloc(n) reserves n bytes and returns a pointer to the block, or NULL if there is no memory. It is declared in <stdlib.h>. The initial content is garbage. Every reserved block must be released exactly once with free. The recommended pattern to compute the size is malloc(count * sizeof *ptr): using sizeof of the pointed object avoids errors if you change the type later. And always check that the result is not NULL before using it.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
size_t count;
printf("How many numbers? ");
if (scanf("%zu", &count) != 1 || count == 0 || count > 1000000) {
printf("Invalid count.\n");
return 1;
}
int *numbers = malloc(count * sizeof *numbers);
if (numbers == NULL) {
printf("Out of memory.\n");
return 1;
}
long long sum = 0;
for (size_t i = 0; i < count; i++) {
numbers[i] = (int)(i * i);
sum += numbers[i];
}
printf("sum of squares = %lld\n", sum);
free(numbers);
numbers = NULL; /* avoids using a dangling pointer by mistake */
return 0;
}calloc and realloc
calloc(n, size) reserves space for n elements and sets it all to zero; it also checks that n * size does not overflow, which makes it safer when n comes from outside. realloc(ptr, new_size) changes the size of a block, keeping the content; it may move the block to another address. The trap: if it fails it returns NULL but the original block is still alive, so if you do ptr = realloc(ptr, ...) and it fails, you lose the pointer and leak memory. Store the result in a temporary variable.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
size_t capacity = 2;
size_t length = 0;
int *items = calloc(capacity, sizeof *items); /* zero-filled */
if (items == NULL) {
return 1;
}
for (int value = 1; value <= 10; value++) {
if (length == capacity) {
size_t new_capacity = capacity * 2;
int *bigger = realloc(items, new_capacity * sizeof *items);
if (bigger == NULL) {
free(items); /* original block is still valid */
return 1;
}
items = bigger;
capacity = new_capacity;
}
items[length++] = value * 10;
}
printf("length = %zu, capacity = %zu\n", length, capacity);
printf("last = %d\n", items[length - 1]);
free(items);
return 0;
}The four classic errors
- Memory leak: reserving and not freeing; the program consumes more and more memory
- Use after free: reading or writing a block that was already freed
- Double free: calling free twice on the same block
- Heap overflow: writing beyond the reserved size
- Freeing something that did not come from malloc, such as a local array, is also an error
A useful example is duplicating a string: you reserve strlen(s) + 1 bytes (do not forget the terminator) and copy. That function, strdup, is part of C23, but it is good to know how to write it. The caller receives a new block and is responsible for freeing it.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static char *duplicate(const char *s) {
size_t size = strlen(s) + 1; /* +1 for '\0' */
char *copy = malloc(size);
if (copy == NULL) {
return NULL;
}
memcpy(copy, s, size);
return copy;
}
int main(void) {
char *name = duplicate("dynamic text");
if (name == NULL) {
return 1;
}
name[0] = 'D';
printf("%s\n", name);
free(name);
return 0;
}✎ Мои заметки
Сохранено только в этом браузере. Войдите, чтобы хранить в аккаунте.0/5000 символов