Skip to main content

Stack vs Heap memory

Updated 3 min readMarkdown
Stack vs Heap memory

පරිගණක ක්‍රමලේඛනයේදී (Computer Programming) memory කළමනාකරණය (Memory Management) ඉතා වැදගත් වේ. ඕනෑම මෘදුකාංගයක් ක්‍රියාත්මක වන විට, එයට අවශ්‍ය දත්ත ගබඩා කර තබා ගැනීමට RAM (Random Access Memory) භාවිතා කරයි.

මෙම මතකය(Random Access Memory) ප්‍රධාන වශයෙන් කොටස් දෙකකට බෙදා වෙන් කර ඇත:

  1. ස්ටැක් මෙමරි (Stack Memory)

  2. හීප් මෙමරි (Heap Memory)


1. ස්ටැක් මෙමරි (Stack Memory) යනු කුමක්ද?

ස්ටැක් මෙමරි යනු ඉතා පිළිවෙලට දත්ත ගබඩා කරන මතක කොටසකි. මෙය ක්‍රියාත්මක වන්නේ LIFO (Last In, First Out) හෙවත් “අන්තිමට ඇතුල් කළ දේ මුලින්ම පිටවේ” යන නීතියට අනුවයි.

මෙය ක්‍රියාත්මක වන ආකාරය

ඔබ යම් method/function එකක් call (invoke) කරන විට:

  • එම method එකට අදාළ local variables

  • method call information (stack frame)

ස්ටැක් එක තුළ​ට Push කරයි.
method එක අවසන් වූ වහාම එම දත්ත Pop කර ඉවත් වේ.

Code Example

void myMethod() {
    int x = 10;
    int y = 20;
}

myMethod() run වෙද්දී x සහ y stack එකේ තබනවා.
method එක අවසන් වුණාම ඒවා මැකෙනවා.

ප්‍රධාන ලක්ෂණ

  • වේගවත්යි – memory allocation/deallocation ඉතා වේගවත්

  • ස්වයංක්‍රීයයි – programmer intervene කරන්න ඕන නෑ

  • සීමිත ඉඩ – වැඩියෙන් data දැම්මොත් Stack Overflow error


2. හීප් මෙමරි (Heap Memory) යනු කුමක්ද?

හීප් මෙමරි යනු විශාල memory pool එකකි. මෙහි data store වන්නේ dynamic විදිහටයි. මෙය ප්‍රධාන වශයෙන් Objects සහ complex data structures සඳහා භාවිතා කරයි.

මෙය ක්‍රියාත්මක වන ආකාරය

Object එකක් create කරන විට (new keyword):

  • Object data → Heap එකේ store වෙන​වා

  • Reference (heap address) → Stack එකේ store වෙන​වා

Code Example

class Person {
    String name;
}

Person p = new Person();
p.name = "Kamal";

Memory layout:

STACK                     HEAP
p ───────────────▶        Person Object
                          name = "Nimal"

ප්‍රධාන ලක්ෂණ

  • ධාරිතාව විශාල​යි

  • ප්‍රධාන වශයෙන් Objects සහ complex data structures සඳහා භාවිතා කරයි

  • Slower than stack

  • Java/Python වල Garbage Collector(GC) memory clean කරනවා

  • C/C++ වල programmer manage කරන්න ඕන


3. Stack සහ Heap එකට එකට බලමු

int a = 5;

Person p = new Person();
p.name = "Nimal";
STACK                     HEAP
a → 5

p ───────────────▶        Person Object
                          name = "Nimal"

Stack vs Heap — Comparison Table

විශේෂාංගයස්ටැක්හීප්
Storage TypeTemporaryDynamic / Long-term
SpeedFastSlower
SizeLimitedLarge
Managed BySystem (Auto)GC / Programmer
StoresLocal variables, referencesObjects
ErrorStack OverflowMemory Leak

සරල උදාහරණයක්

  • Stack = පොත් ගොඩක් එක උඩ එක තැබුවා වගේ

  • Heap = විශාල ගබඩා කාමරයක් වගේ


සාරාංශය

  • Stack → temporary, fast, auto managed

  • Heap → objects, large memory, GC managed

About the author

  • Hi, I’m Harsha Fernando. I love coding, learning new tech, and sharing knowledge in Sinhala. I write about programming, web development, and real-world projects.

No comments yet. Be the first to comment.

More from this blog