Like a queue, you can’t access items in the middle of the stack only those at the end of the queue.Ī stack is basically a one-ended queue. Stack vs QueueĪ queue works on the First In First Out (FIFO) principle so it has some similarities to a stack. With a stack, you only have access to the last item you added to it. In an array, you can access any item in the array using its index. All of those variables are sitting in the previous block and are therefore inaccessible. This is why when you call a new method you don’t have access to any of the variables that were used in the calling method. You can only ever read the data from the item on the top of the stack. The stack works on the Last In First Out (LIFO) principle. You can add and remove books from the top of the stack but you can’t access any in the middle or the bottom. The stack can be viewed similarly to a stack of books. To properly understand the call stack you need to understand the stack data structure. Once the execution of that method has finished it is removed (popped) from the call stack and execution is returned to the previous method. To hold the values (or pointers) of local variables used in the methods.Įach time you call a method in your application it is added (pushed) to the call stack along with any local variables that are declared in the call stack. To keep track of the method that control should return to once execution has finished for the current method. The stack has 2 main responsibilities when your program is running: This is why if you run a recursive function in an infinite loop you will get a stack overflow exception.Įven though the stack and heap take up space towards each other the operating system will make sure that they don’t consume the same address space. However, the size of the stack is generally fixed when the application is compiled. Items are added to the stack moving downwards going from high address space to low address space. The stack is located in the high address space. As shown in the diagram the heap grows upwards and more space is allocated to it as you need it, either manually by the programmer (C/C++) or automatically by the runtime. The stack and heap both share the same address space. □ Don't miss out on this week's issueĪt runtime, your compiled code is stored in memory as execution instructions in the bottom part of memory (machine code). You might like my free weekly newsletter, The Curious Engineer, where I give career advice and tackle complex engineering topics. □ Are you looking to level up your engineering career?
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |