C++ Tutorial: static vs dynamic memory

preview_player
Показать описание
It can be confusing to know which type of memory to use in your programs. In this video I explain the differences between static and dynamic memory, and provide an example application of dynamic memory.

static memory is allocated on the stack at compile-time. This means it is fixed in size for the duration of the program.

dynamic memory is allocated on the heap at run-time. This means the size of the memory you get is determined /after/ the program has already started running.

this benefit comes at a cost of requiring extra work. A pointer will be needed as well as two new key words, new and delete. It's up to the programmer to manage this memory in C++ and make sure there are no memory leaks.
Рекомендации по теме
Комментарии
Автор

Regarding the 0:53, what if my program is:

int main(){
int n;
cin << n;
int array[n];
}

Here the user responsible for the size of memory

matx
Автор

~10:30 static allocation doesn't happen on the stack, but in a separate static data area. Local variables and function/method parameters of course ARE on the stack, those are called "automatic" but the keyword for this, 'auto' was so seldom used that they re-purposed it into the stand-in for type inference in declarations instead in 2011. A minor terminology detail, this is a good video. Both static and automatic (stack) usage can happen for anything that is a primitive, built-in type or an array of something of some size known at compile time. Actual static allocation is considered a major anti-pattern by many, when I first leaned C as a kid, we were taught never to use static allocation because it would break multi-threading, in the early 90's we were avoiding it because it broke multi-user stuff on Mainframe OS's.
Stack / automatic variable usage was of course just fine, so in a way it isn't great to use the term static to cover automatic (or simply 'stack') allocation on the stack -- it may not be loved, but it is a legitimate and real option for placing objects of known size at compile time.

jvsnyc
Автор

static allocation memory must have keyword static and store in static memory, its different from automatic memory allocation which store in stack memory.

sipanmohammed
visit shbcf.ru