Stack vs Heap

Sdílet
Vložit
  • čas přidán 26. 07. 2024
  • How Stack and Heap Memory is used by programs

Komentáře • 106

  • @cashcow3996
    @cashcow3996 Před 5 lety +11

    finally a man with some serious content on his channel...much appreciated sir

  • @matthewso1315
    @matthewso1315 Před 4 lety +66

    Basically when your program there are 3 components code, stack, heap. The programming language code is complied by a compiler to machine code. The code can aceess variable directly from the stack but the function such as malloc will be allocated in the heap. The heap has a pointer in the stack so the stack can be the median where the code can access the heaps memory. Stack has static(size) memory allocation while heap has dynamic(size) memory allocation. Both are stored in the RAM
    Youre welcome

    • @richardstevenson371
      @richardstevenson371 Před 4 lety +2

      Thank you, that was so much faster...

    • @computadorhumano949
      @computadorhumano949 Před 3 lety

      stack store static data? and whereas heap store dynamic?

    • @computadorhumano949
      @computadorhumano949 Před 3 lety

      i got it, thx

    • @jimshtepa5423
      @jimshtepa5423 Před 2 lety +1

      Here is how someone just copied and pasted your comment as his own and generating likes=)) czcams.com/video/bbym08gSWvQ/video.html

    • @GuilhermeDavino
      @GuilhermeDavino Před měsícem

      @@computadorhumano949 raro encontra br nesses assuntos kkkkkkk tmj

  • @lordgaulo6520
    @lordgaulo6520 Před 8 lety +26

    this is the best explanation I have seen so far

  • @IreshDissanayakaM
    @IreshDissanayakaM Před 5 lety +5

    What a great explanation. Got a much clearer understanding than I had before.

  • @Ahmad-hq7oz
    @Ahmad-hq7oz Před 6 lety +5

    One of the great and simple explanation, thank you.

  • @JasonKim1
    @JasonKim1 Před 2 lety +11

    Summary
    - Your code becomes machine code via compilation
    - Machine code accesses data in stack directly and data in heap indirectly
    - Stack size is determined during compilation and is static. Example: variables and functions you declared in your program
    - Heap size is determined during runtime and is dynamic. Example: REST responses or data from a file you load to your program during runtime

  • @mijbulbaharjibon8262
    @mijbulbaharjibon8262 Před 5 lety

    Thanks Mr. Abdul Bari for your informative and comprehensive lecture. Love from Bangladesh.

  • @codelinx
    @codelinx Před rokem +2

    Great explanation. I'm still a little new to understanding memory allocation along with space time complexity, but your videos are so well explained.

  • @Trippykiyay
    @Trippykiyay Před 5 měsíci

    Your videos are great. I am so glad I ran into your channel.

  • @ManuLuck82
    @ManuLuck82 Před 2 lety +1

    Thanks a lot! Nice, coincise and clear explanation.

  • @talibbamasdoos5661
    @talibbamasdoos5661 Před 6 lety +2

    Awesome sir!!!!....
    Sir please do upload the videos of the programs of stack using array and link list .....please....ur an outstanding teacher...straight towards the target👍👍

  • @alabhsumaniya2870
    @alabhsumaniya2870 Před 8 lety +6

    nailed it..! crystal clear explanation about heap and stack...

  • @pijushbasak4273
    @pijushbasak4273 Před 3 lety

    Your explanation is always good.

  • @rajesh6353
    @rajesh6353 Před 6 lety

    Simple but awesome explanation !!!

  • @isuridranaweera2714
    @isuridranaweera2714 Před 4 lety

    Thank you sir... for the great & simple explanation

  • @justinliu7605
    @justinliu7605 Před 8 lety +1

    that was perfect, best one I have watched regarding stack and heap explanation

  • @huanshao2165
    @huanshao2165 Před 4 lety

    Great explanation! Thank you!

  • @FatalAnimal
    @FatalAnimal Před 5 lety +1

    Thanks for the excellent explanation =)

  • @sameeruddinkadri
    @sameeruddinkadri Před 5 lety

    Abdul bari assalamalaikum your explanation is nice keep it up !

  • @videomania1635
    @videomania1635 Před 3 lety

    Thanks for sharing your knowledge.
    U r genius

  • @bradkoenen1699
    @bradkoenen1699 Před 5 lety +1

    Just watched. Thanks!

  • @shameerhameed9039
    @shameerhameed9039 Před 7 lety

    Thanks for explaining the difference

  • @chandansharma6849
    @chandansharma6849 Před 4 lety

    Perfect , you killed it sir😎😎😎

  • @joshmitchell7406
    @joshmitchell7406 Před 5 lety +5

    Great video. I feel like I finally understand the purpose of pointers haha.

  • @bellalmahtab8220
    @bellalmahtab8220 Před 5 lety +1

    absolultely marvellous sir

  • @sukursukur3617
    @sukursukur3617 Před rokem

    Haha, i am taking your udemy course at the moment. CZcams recommended this video. And i recognised your voice

  • @aditydud
    @aditydud Před 6 lety +2

    excellent explanation sir

  • @fahadismail7476
    @fahadismail7476 Před 7 lety

    best of the bests sir..!!

  • @manuk2803
    @manuk2803 Před 2 lety +1

    Nice tutorial!

  • @mdnayabalam4940
    @mdnayabalam4940 Před 6 lety

    Nailed it sir...you are among the best teachers in the youtube

  • @armaghansikandar6435
    @armaghansikandar6435 Před 8 lety +1

    Excellent!!

  • @mdatifbinkarim3877
    @mdatifbinkarim3877 Před 3 lety

    It is called the teaching method. Beyond my expectation.

  • @subhadrayadav178
    @subhadrayadav178 Před 6 lety +111

    play at 1.5X and thank me later

    • @petruciucur
      @petruciucur Před 5 lety +11

      1,25

    • @RandomAlias1
      @RandomAlias1 Před 5 lety +7

      hahaha seriously thank you.. I was like "this dude speaks too slow".. But it's a good video nonetheless

    • @code.r
      @code.r Před 5 lety +3

      @@RandomAlias1 he is not a Dude..

    • @premce45
      @premce45 Před 5 lety +1

      1.25

    • @baref0ot455
      @baref0ot455 Před 5 lety

      LOL Thank you

  • @tahairanaheed8367
    @tahairanaheed8367 Před 6 lety +1

    zaberdast sir thank u sooo much

  • @kaustubh.sharma
    @kaustubh.sharma Před 7 lety

    Awesome sir!!

  • @a.v7998
    @a.v7998 Před 3 měsíci

    Excellent Video!!

  • @tarangmishra7391
    @tarangmishra7391 Před 6 lety +1

    Thank you so much....

  • @video-vocabulary
    @video-vocabulary Před 4 lety

    Brilliant explanation

  • @jakyshan70
    @jakyshan70 Před 7 lety +1

    great video thnks alot

  • @akashpatil5086
    @akashpatil5086 Před 4 lety

    suppose if i declare a variable in a instance area but i initialize it in a method then in which area that variable will get stored? heap or stack or ?

  • @mohammedal-moayed6516
    @mohammedal-moayed6516 Před 5 lety +1

    We declared the pointer to point to a memory in the heap with the size of 10 (malloc(10)). So, why at the end you mentioned that the size of the heap is decided
    at the run time?

    • @NewAgeKarma
      @NewAgeKarma Před 5 lety +2

      Maybe you could think of "10" as a variable. Something like
      size_t someSize;
      int *p;
      p = malloc(someSize);
      /* someSize may get values from intermediate functions in the code which makes it dynamic but not static(may be predefined for something like int,char,float etc;) */

  • @anshulhedaoo8332
    @anshulhedaoo8332 Před 7 lety

    excellent explanation

  • @user-do9gq7go1p
    @user-do9gq7go1p Před 7 měsíci

    As we have already decided to allocate 10 bytes of memory to the pointer statically.Then how is it dynamic allocation

  • @ShivaNandam597
    @ShivaNandam597 Před 5 lety

    Java doesn't support either Malloch or pointers , this case how heap memory can access sir?

  • @syedfamily1
    @syedfamily1 Před 3 lety

    Thanks for great video

  • @guliyevshahriyar
    @guliyevshahriyar Před rokem

    Thank you very much teacher.

  • @jcnarasimhan4218
    @jcnarasimhan4218 Před 6 lety +1

    Beautifully explained...heap memory and stack memory.
    Wondering what software you used for screendrawing

  • @LilJollyJoker
    @LilJollyJoker Před 6 měsíci +1

    Thank you!

  • @gateeasycse
    @gateeasycse Před 5 lety

    sir memory are byte addressable .is each address static or not ? .is memory access designed during hardware design ? plz explain

  • @computadorhumano949
    @computadorhumano949 Před 3 lety

    how i can figure out if my memory is stored in heap or stack?

  • @hrishikeshmallick3508
    @hrishikeshmallick3508 Před 4 lety +2

    I really like ur style of teaching sir.

  • @gateeasycse
    @gateeasycse Před 6 lety

    when heap memory dropped.is only switch off the computer ?

  • @VinothKumar-zl2ht
    @VinothKumar-zl2ht Před 4 lety

    Hi Stack should be at the top of memory right ?

  • @gateeasycse
    @gateeasycse Před 6 lety

    once function execution completed all stack and heap memory are dropped .am I right sir

  • @naveenthotam458
    @naveenthotam458 Před 6 lety +1

    nice too good

  • @dr.shabbirhassan7128
    @dr.shabbirhassan7128 Před 5 lety

    Sir I think heap memory can also be access directly if we declare out pointer to heap globally. If it's write kindly comment me!!!

  • @adambillen5164
    @adambillen5164 Před 2 lety

    good explanation!

  • @AmitKumar-we8dm
    @AmitKumar-we8dm Před 4 lety

    Can you explain this heap concept in context of java.

  • @rzwnhmd
    @rzwnhmd Před 4 lety

    Why is the memory divided into stack and heap? is it for faster code execution or do they wanted to have a special memory allocation for malloc and pointers or is the reason something else?

    • @humnawahumsafar5083
      @humnawahumsafar5083 Před 3 lety +1

      Because we have different requirements.
      We may need to store a large array or just a small variable name. It will be unwise to allocate same memory for them. Some benefits of having different storage type in RAM.
      1. Provides access restrictions in RAM.
      2. Our data, variable can be provided different kind of accessibility, local variables which are stored in stack are more readily available then global variable in heap.
      3. Storing in stack is less costlier than heap.

  • @boogeyman9824
    @boogeyman9824 Před 4 lety

    Sir please do a complete lecture on data structures through c concept

  • @aimhighjavapythonbuttaj9972

    Fine explanation

  • @hammadvideosmaker7161
    @hammadvideosmaker7161 Před 8 měsíci

    love you sir😍😍

  • @Nick-ui9dr
    @Nick-ui9dr Před rokem

    Actually as I told u I no programmer... Programming se door door tak mera koi lena dena nahin hai... Woh kya hai ki ek jab chotey the ...young the toh humare badey bhai ne ek computer leke de diya tha humko... Ush samay Pentium 1 chala tha naya naya... 133 MHZ I guess.. Toh bhai woh aa gaya... Ush samay Windows 3.1 chalta tha lekin humara wala DOS loaded aaya tha... Koi nayi Indian company ne launch kiya tha... uske baad band bhi ho gayi woh company sayad. 😂 Some PCL or whatever CL.
    Toh hum kisi computer waale ko toh jaantey nahin the,,, na saath tha. DOS aaya tha... Ushme 2-3 hi utility hoti ... Ek Edit.. doosra QBASIC ...3rd woh thakeli Debug utility. Hum Debug ke piche pad gaye. 6 mahine room band kar ke debug phad diya humne. LOL
    Arey woh tab virus surus bade chaltey the ant pant jhant type ke.. Ek do thore humaare system mein bhi aaye gaye the... Die hard 2 aur ek aadh woh Boot sector MBR waale the. Bas unhi ke piche pil gaye. Aur ush debug utility mein koi help file nahin aati saath mein. Bas woh /h maar ke woh char commands ke naam bata deta. Achcha woh 8086 based thi DOS wali debug utility. Tha pentium humaare paas toh woh karta kya tha... joh 386 aur above ke instructions the unko ??? dikha deta tha... Hum paresaan 2 mahino tak ki yeh saala khon sa instruction hai. Ab step in karo to woh har baar alag alag instruction ke hisaab se alag alag kaam kar raha tha. Yahan koi consistency nahin dikhai de rahi thi... Kabhi koi register badal jaye kabhi koi Eflag ki bit on ho jaye.. Hu, paresaan... Hai kya saala yeh.... Ek aadh MCA BCA waale the colony mein... unke paas gaye ki bhai yeh kaun sa instruction hai. Unko debug utility ka hi nahin maloom. 😃
    Kher ayessey hi gaadi chalti rahi... Phir ek micro processor ki kitab laye ushme saare pentium ke instructions diye the... Kitab bechne wala bhi saala humse tafri le raha tha,,, Kyun bhai processor banaoge? 😂🤣
    Woh uska kuch naam tha na Pentium Micro processors and micro controllers kar ke. Kher ishi tarah ke utt patang chalta raha.... Akhir jaake humne Pura Intel Manual tab ka chat dala. Koi kaam nahin tha... jabardasti faltu sokiya saale ko.... smile
    Matlab C, C++ yah Intel Assembly ki baat aa jaaye toh ayesi koi problem nahin.. phir update ho jayega in no time. But uske baad chut gaya sab kuch duniyadari ke chalte. Aajkal phir retirement age aaye gayi hai toh phir utha liye hain purane sokh. Abkil dekho kya hota hai. But lots of things has changed aur phir wassey bhi humaari koi formal training toh thi nahin... farzi debugging, assembly...disk formats yeh sab mein ghussey rehtey the tab ke.
    Ab sab badal gaya Windows 11 aa gaya... processor aur OS 64 bit pahunch gaye.. core level pe VM support karne laga processor. Aur phir abkil toh CZcams bhi hai. Tabhi toh graph theory dekh aapke yahan aa gaye. Ish particular page pe toh ayessey hi aa gaye but yes graph theory mein interest hai. Woh mujhe lagta hai kahin kaam aa sakti.. apne phir kisi faltu venture pe. Nahin samjh aayegi toh desi illaaz karenge. Kya problem... Khon sa gate ka exam dena hai. Ek chota mota tool sool try karne ki soch rahe the.. koi disassembler yah system troubleshooting tool yah compiler IDE hi choti moti... Yah kisi team ke pelad sadhu banenge phir... Ek hai dimaag mein mere... QT IDE waale. But saale woh dekhna bhagaa denge merko. Mere personel idea hi bahut dangerous hotey unki na samjh aayenge. 😄
    Chakkar yeh hai yahan koi pharak nahin padta kuch bane na bane .. but woh ek current professional working tool bana aur support kar rahe ...toh tumhaare weirdo ideas jaroori nahin unko samjh aaye U C.
    Anyway miltey rahenge aap se ish purane sokh ke rekindling ke chalte... at least graph theory seory wali jagah. Dekhein toh kya padtey padatey CS waale log.
    Cya bro

  • @samiranroyy1700
    @samiranroyy1700 Před 2 lety

    Thank you so much sir

  • @diabate6929
    @diabate6929 Před 3 lety

    Excellente

  • @Nick-ui9dr
    @Nick-ui9dr Před rokem

    High level programmers really think about memory a lil different way I guess. Though not saying wrong but still if u into assembly u see things lil differently. Like under the hood u cant access any whatsoever memory without pointer or address.. thats the processor way of doing things... thats why it has address and data lines seperatly. No matter what variable u accessing whether from so called heap or stack or even just from data segment u access it through address.
    I no programmer but as I know whatever lil. As you have code section in a file that is memory mapped on program load.. so there is info in file header that where the data section should be as regard to start of program memory and its size. Usually just where code section ends. So if code section is like say 8 MB and it got loaded at 4 mb address space. So the data section will start from 12 mb for whatever length it is define in executable header. Usually compiler store static or global variables in that. Whose address at least relative to program start or data section start it can establish at compile time.
    Next comes default stack memory. Stack memory is OS defined... but sure u can instruct OS loader through executable header for lil more or less I guess. Now whenever u create a variable within a procedure that is not declared static or gglobal comes from stack memory. Compiler generate code for it to refer to stack.
    What is stack frame is... like if u call a routine from somewhere compiler pushes the values of parameters on stack. Like push whatever register holding that value. Or it will load that value in register then push it on stack before call. Thats what call... passing parameter by value. unless u specificaly pass it through pointer instructing compiler to push the address of that variable instead than its copy.
    like for call Add (A, B, &C)
    compiler will push the value of A & B variables on stack but will push the address of C variable on stack rather then its value.
    So the code will be...
    Push A
    Push B
    Push address of C
    call Add
    this call will now automatically push the address of next instruction after call into the stack. Thats what call instruction of processor do.... now the Ret statement at end of that called function will return or branch to that address later on when call is finished.
    in add function...
    Add function
    {
    so lets say before call SP (stack pointer) register was at 1000.... now after 3 pushes if 4 byte long each plus lets say if 32 bit program so more byte of address that got pushed when call instruction was excuted.. so all total SP will be now 1000 - 16 bytes ...stack or stack pointer works reverse way u see.... from top to bottom.
    first work of compiler generated code is usually to move current SP register value in BP (Base Pointer) register to establish a base from which it will access parameters or local variables.
    Now compiler generated code will futher push down stack pointer by amount of bytes it needed for local variables of this procedure. Say there is one 4 byte size variable. code will do
    S4 = SP - 4
    if that local variable is initialised it will put that value through some register into that stack location. Now as u see BP is pointing at 1000 - 16 ... but SP at 1000-20 . But thats was a general norm of old times. Now with 64 bit compilers ..u may easily find procedures passing values through registers intstead of stack to speed up things... or directly accessing stack memory of prev procedure internally.
    Anyway if there are more than one local variables... ocde will usually access them through adding proper offset to BP register... wheas it will deduct appropriate offset to access passed parameter through BP since BP hold top address than those passed parameters. But again nobody says that can only be like that... main thing is accessing right location ..with what register or what ay dont count that much as far as there is consistency within program.
    Now at the end of called procedure... compiler generated code will again restore SP register and return. Return will take u back to next instruction after the call instruction. Return values usually get passed back in AX or EAX register. Or now a days 64 bit RAX register for 64 bit programs.
    so whether its from heap or stack or any kinda memory as far as processor is concerned it always uses addressing mode through some register to load that variable value in some register before processing then it will store that value back to its location ...but since for local variables that location got invalid after the call so accessing them makes no sense. For static variables... it will always generate instruction to load that value from certain location in data section. Now how it accomplish this is by generating a code with offset relative to base of program. And create a relocatable entry for it in file header. So when loader loads that program it patches the program after loading the file like at 4mb location ..so it will add that 4mb offset to that offset.. so it will become the right address in instruction that is 4mb + offset from start of program.
    Now heap... heap is a memory that u get allocated by calling malloc alloc or new in C or C++. Now there are functions or library in OS that basically provide that functionality or why it is basically called heap.. So there are variety of heap functions in windows. Then there are VirtualAlloc in system level libraries (kernel). function that those user level OS heap function themshelves call into to allocate memory. Now there is some compiler generated code in your program those malloc or new routines that handles those memory for u. So they allocated from OS heap functions and provide them to u through malloc or new functions. Now since they dynamic in nature... cause u cant tell beforehand where the OS will allocated this heap memory. So the only way is to address it indirectly through some register ...so what compiler generated code can do is to address it thorugh some register and then load that register with that memory address before calling cause OS returns the address of memory on sucessful allocation. So all compiler need to do is to somehow pass on that address to that procedure code. Technically u can do it lots of ays... Even though u call certain registers by certain names like SI (source index) DI(destination index) SP (stack pointer) BP base pointer but u can do with any register whatsoever with lil or more difficulty. But they optimised for specific purposes. Certain instruction auto increment those Index register so u need not have to increment them after accessing a array memory in sequencial way. But u certainly can do same thing with any register. and then inc that register by that size.
    This can go on for ages ..but lets conclude. 😉

  • @zoherdaher4059
    @zoherdaher4059 Před 3 lety

    legendary

  • @sravankumarg2095
    @sravankumarg2095 Před 6 lety

    Super

  • @1987ckg
    @1987ckg Před 4 lety

    What is the Total Size of our C program?

  • @gateeasycse
    @gateeasycse Před 5 lety

    sir global variable where it is stored

  • @manojsuryawanshi1334
    @manojsuryawanshi1334 Před 5 lety

    In your example *p declared in stack .this pointer also take memory in stack. So why used the heap.. please give me ans fast..

    • @tanveerhasan2382
      @tanveerhasan2382 Před 5 lety

      pointer p is only storing the memory address of the heap memory

  • @ingrooo
    @ingrooo Před 5 lety

    fucking hell!!!! thank you very much man! nice

  • @yutaitadori7318
    @yutaitadori7318 Před 3 lety

    ❤️

  • @sachinpatil-ky8gy
    @sachinpatil-ky8gy Před 6 lety

    bit fast is better

  • @gateeasycse
    @gateeasycse Před 5 lety

    sir memory are byte addressable .address of memory is fixed or not

  • @copypaste3526
    @copypaste3526 Před 5 lety

    It‘s very broken english. Hard to follow that way. Als the writing is not easy to read.

  • @moshiramadhan1082
    @moshiramadhan1082 Před 2 lety

    Brilliant explanation