🚀 C# ile Programlamaya Giriş: Kodlamaya İlk Adımını At, Kendi Projelerini Geliştirmeye Başla!
00HOME
07GLOSSARY 08TAGS ♡MY LIST ⌕SEARCH
TRENG

Memory management: malloc, free and their traps

Allocate memory with malloc, calloc and realloc for data whose size is only known at run time, give it back with free, and learn to recognise memory leaks, dangling pointers and double frees.

Think of a data logger where the user chooses the measurement duration. Today they may want 10 samples, tomorrow 10 000. Writing double olcum[10000]; usually wastes memory, and it still isn't enough for sample number 10 001. The solution is to request memory while the program is running, exactly as much as needed. This is called dynamic memory. C gives you full control here, but it also leaves the responsibility to you: giving back the memory you took is your job.

Stack and heap: two separate memory areas

  • Stack: local variables of functions live here. They are cleaned up automatically when the function ends. It is fast but limited in size.
  • Heap: memory requested with malloc comes from here. It stays allocated until you call free; it lives on even after the function ends.

malloc and free

#include <stdio.h>
#include <stdlib.h>

int main(void) {
    int n;
    printf("Ornek sayisi: ");
    if (scanf("%d", &n) != 1 || n <= 0) return 1;

    double *gerilim = malloc(n * sizeof *gerilim);
    if (gerilim == NULL) {
        printf("Bellek ayrilamadi!\n");
        return 1;
    }

    double toplam = 0.0;
    for (int i = 0; i < n; i++) {
        gerilim[i] = 220.0 + i * 0.5;      // olcum yerine ornek veri
        printf("%d: %.1f V\n", i, gerilim[i]);
        toplam += gerilim[i];
    }
    printf("Ortalama: %.2f V\n", toplam / n);

    free(gerilim);
    gerilim = NULL;
    return 0;
}
Ornek sayisi: 5
0: 220.0 V
1: 220.5 V
2: 221.0 V
3: 221.5 V
4: 222.0 V
Ortalama: 221.00 V
  • malloc(bytes) reserves the requested number of bytes and returns the starting address. We calculated the number of bytes with n * sizeof *gerilim: "n items of the type gerilim points to". If the type changes later, this expression adapts automatically.
  • If there isn't enough memory, malloc returns NULL. Using it without checking means writing to a NULL address and crashing.
  • You can use the returned pointer just like an array with gerilim[i]; the equality dizi[i] == *(dizi + i) from the pointers lesson holds here too.
  • free(gerilim) gives the memory back. Setting the pointer to NULL afterwards is a good habit.

calloc and realloc: zeroed allocation and growing

calloc(count, size) allocates like malloc but sets every byte to zero. realloc grows or shrinks an existing block. Let's double the size of a log buffer whenever it fills up, since we don't know how many readings will arrive:

#include <stdio.h>
#include <stdlib.h>

int main(void) {
    int kapasite = 2, adet = 0;
    int *kayit = calloc(kapasite, sizeof *kayit);
    if (kayit == NULL) return 1;

    int gelen[5] = {512, 498, 530, 505, 487};
    for (int i = 0; i < 5; i++) {
        if (adet == kapasite) {
            int *yeni = realloc(kayit, 2 * kapasite * sizeof *kayit);
            if (yeni == NULL) {
                free(kayit);
                return 1;
            }
            kayit = yeni;
            kapasite *= 2;
            printf("Kapasite %d oldu\n", kapasite);
        }
        kayit[adet++] = gelen[i];
    }
    printf("%d kayit, son: %d\n", adet, kayit[adet - 1]);
    free(kayit);
    return 0;
}
Kapasite 4 oldu
Kapasite 8 oldu
5 kayit, son: 487

We first stored realloc's result in a separate pointer called yeni. Had we written kayit = realloc(kayit, ...) directly and realloc failed, it would return NULL; the address of the old block would be lost and that memory could never be freed. realloc may move the block to a different address, so don't keep using the old address.

Three big dangers

1. Memory leak: if allocated memory is never given back, the program uses more and more memory as it runs. In monitoring software that runs continuously, this means a crash days later.

void olcum_yap(void) {
    double *tampon = malloc(100 * sizeof *tampon);
    if (tampon == NULL) return;
    /* ... islem ... */
}   /* free yok: her cagrida 800 bayt kaybolur */

2. Dangling pointer: a pointer that points to memory that is no longer valid. A pointer used after free, or a function that returns the address of a local variable, are examples:

int *hatali(void) {
    int deger = 42;
    return &deger;   /* fonksiyon bitince deger yok olur! */
}

3. Double free: freeing the same block twice corrupts the heap's internal structure and can crash the program. Setting the pointer to NULL after free reduces this risk, because free(NULL) does nothing and is safe.

On Linux you can catch these bugs by compiling with gcc -g -fsanitize=address or by running the program under valgrind ./program; both show leaks and invalid accesses with line numbers.

On embedded systems: the ATmega328P (Arduino Uno) has only 2 KB of SRAM in total. In memories that small, frequent malloc/free calls break the heap into fragments, and when a large block is requested there may be no room for it. That's why embedded software mostly prefers fixed-size arrays. Safety-oriented coding rules such as MISRA C also forbid or tightly restrict dynamic memory.

Common mistakes

Using memory after free: accessing an address after giving it back is undefined behaviour. Sometimes the old value can still be read and the bug stays hidden; that's what makes it so dangerous.

  • Forgetting sizeof: malloc(n) allocates n bytes, not n doubles. The correct form is malloc(n * sizeof *p).
  • Skipping the NULL check: check the result of every malloc, calloc and realloc.

Exercise

Read the number of measurements from the user first, then that many current values (A). Keep the values in an array allocated with malloc; print the average and the largest current with two decimals. Don't forget to free the memory.

Hint: check the return value of every scanf in the reading loop. If there's an error, call free before exiting as well.

Solution

#include <stdio.h>
#include <stdlib.h>

int main(void) {
    int n;
    printf("Olcum sayisi: ");
    if (scanf("%d", &n) != 1 || n <= 0) return 1;

    double *akim = malloc(n * sizeof *akim);
    if (akim == NULL) return 1;

    for (int i = 0; i < n; i++) {
        if (scanf("%lf", &akim[i]) != 1) {
            free(akim);
            return 1;
        }
    }

    double toplam = 0.0, enb = akim[0];
    for (int i = 0; i < n; i++) {
        toplam += akim[i];
        if (akim[i] > enb) enb = akim[i];
    }
    printf("Ortalama: %.2f A\n", toplam / n);
    printf("En buyuk: %.2f A\n", enb);

    free(akim);
    return 0;
}
Olcum sayisi: 4
2.5 3.1 2.8 4.0
Ortalama: 3.10 A
En buyuk: 4.00 A

You've learned to take memory at run time, give it back, and spot the three most common dangers. In the next lesson we'll keep related data together with struct and save sensor readings to a CSV file.

// Spot the bug +10 XP

Exactly one line below is wrong. Click the faulty line.

// Mini quiz

Click an option; you will see right away, with the reason, whether it is correct or not.

1. What does malloc return if it cannot allocate the requested memory?
2. Which statement is true about the pointer p after calling free(p);?
3. What is the main feature that sets calloc apart from malloc?

Mark it when you finish: your progress is saved and you earn +20 XP.

Tip: ← → keys let you move between lessons.