I'm trying to learn the basics of how a computer works. Computer programs seem to be loading variables onto the stack a lot of the time (and then running scopes within scopes inside the stack. ) It is easy to see how a static array would be stored within a stack. But, dynamic arrays, if their size is increased beyond the memory that was already allocated for it, have to be moved to a new memory location (pointer pointing to new array with the new length and old elements copied to it. ) This does not seem to work with the stack. I have heard of the "heap" being thrown around, and I assume the actual dynamic arrays would have to be stored at something different than the stack, and just keeping the pointer to it in the stack. Anyone want to elaborate on how dynamic arrays are usually handled in memory, so that I can then read more about it? My level of understanding is novice but I am a relatively fast learner and prettty dedicated.
Asked
Active
Viewed 153 times
0
-
Does this answer your question? [memory allocation in Stack and Heap](https://stackoverflow.com/questions/6770596/memory-allocation-in-stack-and-heap) – wxz Aug 18 '22 at 18:44
-
Well it sounds a lot like what I was thinking. I guess the answer to my question is "yes" more or less. That a distinction is made between static and dynamic memory and a pointer to dynamic one is stored in the static one when using dynamic arrays. Great, nice to be somewhat on the right track to learning the basics eventually. – Program Aug 18 '22 at 19:24
-
*It is easy to see how a static array would be stored within a stack* - nope. Static storage is `.bss` (zero-init) / `.data` (non-zero init from the executable) / `.rodata` (const non-zero init from the executable). Stack memory is literally just the stack, space near the stack pointer (C local variables, aka "automatic storage"). Dynamic storage is allocated with `malloc` / `new`, or at a lower level `mmap` or Windows `VirtualAlloc` to get pages from the OS that could be anywhere in your virtual address space. – Peter Cordes Aug 18 '22 at 20:23
-
Or I guess you mean fixed-size arrays, like a C local variable `int arr[10];` as opposed to C++ `std::vector` that's growable and might need reallocation. Yes, that C array can be on the stack, or in static storage, or in anonymous dynamically allocated with `int *arr = malloc(10*sizeof(int));` with just a pointer to it as a named variable. – Peter Cordes Aug 18 '22 at 20:24
-
just wondering about simplest possible computer machine, and how it evolved and things are organized. it seems to me it is using stack for a lot of things (have not studied it perfectly but why not use stack), but it seemed like it would not work with dynamic arrays, when those need to be recreated at new memory address when they grow beyond current length – Program Aug 18 '22 at 20:46