Thuta Learning
C
AdvancedProgrammingbeginner

Dynamic Memory

ဒီခန်းပြီးရင် ဘာတတ်သွားမလဲ

  • Dynamic Memory ရဲ့C language နဲ့runtime behavior ကိုရှင်းပြနိုင်ရန်
  • Normal, boundary, invalid နဲ့failure cases စမ်းနိုင်ရန်
  • Warnings နဲ့sanitizers အသုံးပြုပြီးsafe C code ရေးနိုင်ရန်

Allocation fail နိုင်ပြီးsuccessful allocation တစ်ခုစီတွင်owner တစ်ခုနဲ့matching free တစ်ကြိမ်ရှိရပါမယ်။

ပိုပြီးနားလည်ထားရမယ့် အချက်

Dynamic allocation တွင်requested size overflow, allocation failure, initialization, ownership transfer, exact-one free နဲ့use-after-free ကိုထိန်းရပါတယ်။ `sizeof *ptr` pattern, checked size arithmetic နဲ့single cleanup path ကိုသုံးပါ။

လက်တွေ့မှာ ဘယ်လိုအသုံးချမလဲ

User count အလိုက်`calloc` array allocate လုပ်ပြီး failure, zero/large count, normal use နဲ့free-after-use ကိုAddressSanitizer ဖြင့်စမ်းပါ။

ဒီသင်ခန်းစာပြီးရင်

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

int main(void) {
    size_t count = 5;
    int *values = calloc(count, sizeof *values);
    if (values == NULL) return EXIT_FAILURE;

    for (size_t i = 0; i < count; ++i) values[i] = (int)(i * 10);
    for (size_t i = 0; i < count; ++i) printf("%d%c", values[i], i + 1 == count ? '\n' : ' ');

    free(values);
    values = NULL;
    return EXIT_SUCCESS;
}
You should see
0 10 20 30 40

ကိုယ်တိုင်စမ်းကြည့်ရန်

User count အလိုက်`calloc` array allocate လုပ်ပြီး failure, zero/large count, normal use နဲ့free-after-use ကိုAddressSanitizer ဖြင့်စမ်းပါ။

Memory/Safety သတိပေးချက်

`malloc` result မစစ်ခြင်း၊size multiplication overflow နဲ့free ပြီးpointer ဆက်သုံးခြင်းကcritical memory bugs ဖြစ်ပါတယ်။

SEI CERT C Coding StandardCarnegie Mellon SEI

ဒီနေရာမှာ လူအများမှားတတ်တယ်

  • `malloc` result မစစ်ခြင်း၊size multiplication overflow နဲ့free ပြီးpointer ဆက်သုံးခြင်းကcritical memory bugs ဖြစ်ပါတယ်။
  • Output တစ်ကြိမ်မှန်ရုံဖြင့် bounds, lifetime, overflow နဲ့ownership အားလုံးမှန်ပြီဟုယူဆခြင်း။

လက်တွေ့လေ့ကျင့်ခန်း

User count အလိုက်`calloc` array allocate လုပ်ပြီး failure, zero/large count, normal use နဲ့free-after-use ကိုAddressSanitizer ဖြင့်စမ်းပါ။

You'll know it worked when: 0 10 20 30 40