Skip to main content

C language


Ram එක වැඩ කරන විදිහ 

 

Q1 කලින් pointer ගැන කතා කරපු නිසා මං ඔයාලගෙන් ප්‍රශ්න 2 ක් අහන්නම්

  1.  පොයින්ට් එකක වැදගත්කම මොකක්ද
  2.  Stack හා  Heap memory  එකේ වෙනස

අද අපි කතාකරන ප්‍රධාන මතෘකා  

  • Ram  එකේ ප්‍රධන කොටස් 3 ( ප්‍රොග්‍රැම් එක රන් වෙන වෙලාවට) 
  • Memory allocation (static vs dynamic) 
  • Code section  
  • Stack, stack frame
  • Heap

      

programe   එකක් වැඩ කරන විදිහ තේරුම් ගන්න ඕන නිසා Ram  එකේ ප්‍රධන කොටස් 3

1.     Code section- program එකට අදාල machine code එක memory එකේ ගබඩා වෙන තැන

2.     Stack- static වෙරියබල් සහ අනිත් function වලට අදාල variable ගබඩා වෙන තැන 

3.     Heap- dynamic වේරියබල් ගබඩා වෙන තැන





Memory allocation  

Variable ගබඩා කිරීමට අවශ්‍ය ඉඩ ලබාදීම ප්‍රධාන ආකාර දෙකකට සිදු කරනවා
  1. Static memory allocation
  2. Dynamic memory allocation 

Static memory allocation

  • int a=12; char b=x; int age= 23; char initial[2];
  • variable එකට ලැබෙන ඉඩ ප්‍රමාණය නිශ්චිතයි

char initial[2];   එකට ලැබිලා තියෙන ඉඩ ප්‍රමාණය අනුව අකුරු 2ක් පමණක් ගබඩා කරන්න පුලුවන්.  හිතන්න අකුරු 2 වැඩි  ප්‍රමාණයක් ගබඩා කරගන්න ඕන වුණා කියලා, හැබැයි අපිට දැන් ඒක කරන්න විදිහක් නෑ මොකද එයාට ලැබිලා තියෙන  ඉඩ ප්‍රමාණය ගබඩා කරන්න පුලුවන් අකුරු 2ක් විතරයි. 


Dynamic memory allocation 


Variable එක declare කරන වෙලාවෙදි අපිට හරියටම variable එකට අවශ්‍ය ඉඩ ප්‍රමාණය දන්නෙ නැත්නම් dynamic memory allocation භාවිතා කරලා variable එක declare කරගන්න. 

  1. malloc()- ptr1 = (int*)malloc(5 * sizeof(int));
  2. calloc()  -ptr2 = (int*)calloc(5, sizeof(int));
  3. realloc()-ptr1 = realloc(ptr1, 8 * sizeof(int));
  4. free() -free(ptr1);
Q2 malloc()  සහ   calloc() වල වෙනස මොකක්ද ?

Code , stack heap මේ තුනම පහත උදාහරණයක් මගින් සරලව තේරුම් ගන්න පුළුවන්.


int main() { int a=20; // stack int* ptr; int* ptr2; ptr = (int*)malloc(1 * sizeof(int)); //heap ptr2 = (int*)calloc(3, sizeof(int)); //heap







        Comments