A static variable inside a function is only allocated once during the lifetime of the program.
So if I have a function like:
void f(int n) {
static int *a = new int[n];
}
and I first call
f(1)
and then
f(3)
how big will the array a be after the second call?
In the Dynamic memory allocation, variables get allocated only if your program unit gets active. Static Memory Allocation is done before program execution. Dynamic Memory Allocation is done during program execution. In static memory allocation, once the memory is allocated, the memory size can not change.
In static memory allocation, while executing a program, the memory cannot be changed. In dynamic memory allocation, while executing a program, the memory can be changed. 4. Static memory allocation is preferred in an array. Dynamic memory allocation is preferred in the linked list.
Dynamically allocated variables live in a piece of memory known as the heap, these are requested by the running program using the keyword "new". A dynamic variable can be a single variable or an array of values, each one is kept track of using a pointer.
Static allocation is what happens when you declare a static or global variable. Each static or global variable defines one block of space, of a fixed size. The space is allocated once, when your program is started (part of the exec operation), and is never freed.
static
variables local a function are initialized the first time control passes through them. The relevant section in the standard is 6.7 [stmt.dcl]. That is, the array will acquire size 1 and keep this size unless you change its size explicitly.
What's nice in C++ 2011 is that initializing the static
variable is also thread-safe: if another thread reaches the instance while the variable is being initialize, the second thread is blocked until initialization is complete.
static
local variables will be initialized when the control flow reaches the declaration for the first time. In this case, since the first time you used 1
as the n
parameter, you'll be allocating size for one int
.
Doing this kind of stuff is a bad idea. You should just use a local, non-static, std::vector
or some other higher level container.
Initialization of static variables within a function only occurs during the first evaluation of the static statement within function. The first time when f
is invoked with f(1)
, the initialization for a
will occur, and it will point to an array of a single int. When f(3)
is called, a
has already been initialized, so the right hand side of:
static int *a = new int[n];
will not be evaluated again, and a
will continue to point to the originally allocated array of size 1.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With