ChatGPT解决这个技术问题 Extra ChatGPT

Difference between static memory allocation and dynamic memory allocation

I would like to know what is the difference between static memory allocation and dynamic memory allocation?

Could you explain this with any example?


b
brice

This is a standard interview question:

Dynamic memory allocation

Is memory allocated at runtime using calloc(), malloc() and friends. It is sometimes also referred to as 'heap' memory, although it has nothing to do with the heap data-structure ref.

int * a = malloc(sizeof(int));

Heap memory is persistent until free() is called. In other words, you control the lifetime of the variable.

Automatic memory allocation

This is what is commonly known as 'stack' memory, and is allocated when you enter a new scope (usually when a new function is pushed on the call stack). Once you move out of the scope, the values of automatic memory addresses are undefined, and it is an error to access them.

int a = 43;

Note that scope does not necessarily mean function. Scopes can nest within a function, and the variable will be in-scope only within the block in which it was declared. Note also that where this memory is allocated is not specified. (On a sane system it will be on the stack, or registers for optimisation)

Static memory allocation

Is allocated at compile time*, and the lifetime of a variable in static memory is the lifetime of the program.

In C, static memory can be allocated using the static keyword. The scope is the compilation unit only.

Things get more interesting when the extern keyword is considered. When an extern variable is defined the compiler allocates memory for it. When an extern variable is declared, the compiler requires that the variable be defined elsewhere. Failure to declare/define extern variables will cause linking problems, while failure to declare/define static variables will cause compilation problems.

in file scope, the static keyword is optional (outside of a function):

int a = 32;

But not in function scope (inside of a function):

static int a = 32;

Technically, extern and static are two separate classes of variables in C.

extern int a; /* Declaration */
int a; /* Definition */

*Notes on static memory allocation

It's somewhat confusing to say that static memory is allocated at compile time, especially if we start considering that the compilation machine and the host machine might not be the same or might not even be on the same architecture.

It may be better to think that the allocation of static memory is handled by the compiler rather than allocated at compile time.

For example the compiler may create a large data section in the compiled binary and when the program is loaded in memory, the address within the data segment of the program will be used as the location of the allocated memory. This has the marked disadvantage of making the compiled binary very large if uses a lot of static memory. It's possible to write a multi-gigabytes binary generated from less than half a dozen lines of code. Another option is for the compiler to inject initialisation code that will allocate memory in some other way before the program is executed. This code will vary according to the target platform and OS. In practice, modern compilers use heuristics to decide which of these options to use. You can try this out yourself by writing a small C program that allocates a large static array of either 10k, 1m, 10m, 100m, 1G or 10G items. For many compilers, the binary size will keep growing linearly with the size of the array, and past a certain point, it will shrink again as the compiler uses another allocation strategy.

Register Memory

The last memory class are 'register' variables. As expected, register variables should be allocated on a CPU's register, but the decision is actually left to the compiler. You may not turn a register variable into a reference by using address-of.

register int meaning = 42;
printf("%p\n",&meaning); /* this is wrong and will fail at compile time. */

Most modern compilers are smarter than you at picking which variables should be put in registers :)

References:

The libc manual

K&R's The C programming language, Appendix A, Section 4.1, "Storage Class". (PDF)

C11 standard, section 5.1.2, 6.2.2.3

Wikipedia also has good pages on Static Memory allocation, Dynamic Memory Allocation and Automatic memory allocation

The C Dynamic Memory Allocation page on Wikipedia

This Memory Management Reference has more details on the underlying implementations for dynamic allocators.


Note: I'd suggest int * a = malloc(sizeof(*a)); instead, to avoid repeating the type of a. This makes things much easier if ever the type of a changes.
Acutally it's called heap but it has nothing to do with heap data structure. Heap in this case means a messy place
"Static memory allocation... Is allocated at compile time" Do you mean allocation size is determined at compile time? Wouldn't the setting aside of memory only happen at runtime?
Hey i have a doubt, If you are still responding :( . What about automatic memory allocation ? Will the compiler also store addresses in data section for these local variables and pass it to the executable. And when the code executes(and enters the scope) these addresses will actually be used as locations of allocated memory. Or does it actually gets allocated at run time only, without any address generation and handling by my compiler ?
@LocalHost Automatic variables are scoped to the lifetime of the context (the curly braces) where they've been defined. that's usually allocated on the call stack at runtime. It's definitely not stored in the data section. You can read the C18 standard here: (6.2.4.5-7) web.archive.org/web/20181230041359/http://www.open-std.org/jtc1/…
B
Bharat

There are three types of allocation — static, automatic, and dynamic.

Static Allocation means, that the memory for your variables is allocated when the program starts. The size is fixed when the program is created. It applies to global variables, file scope variables, and variables qualified with static defined inside functions.

Automatic memory allocation occurs for (non-static) variables defined inside functions, and is usually stored on the stack (though the C standard doesn't mandate that a stack is used). You do not have to reserve extra memory using them, but on the other hand, have also limited control over the lifetime of this memory. E.g: automatic variables in a function are only there until the function finishes.

void func() {
    int i; /* `i` only exists during `func` */
}

Dynamic memory allocation is a bit different. You now control the exact size and the lifetime of these memory locations. If you don't free it, you'll run into memory leaks, which may cause your application to crash, since at some point of time, system cannot allocate more memory.

int* func() {
    int* mem = malloc(1024);
    return mem;
}

int* mem = func(); /* still accessible */

In the upper example, the allocated memory is still valid and accessible, even though the function terminated. When you are done with the memory, you have to free it:

free(mem);

Sure you have control over the lifetime of the variables... you're the one deciding the scope, right?
-1 This answer is wrong. You confuse static and automatic variables.
Your own sentence reads: "Static Allocation means, that the memory for your variables is automatically allocated" This is wrong. Have a look at what the manual page for GNU's libc has to say about it.
Stack allocation is not static. It happens dynamically at runtime, and depends on the runtime conditions of the program, rather than its statically-known properties (which is what static means in C and programming in general). Static allocation is what the compiler can infer, without actually running the program. I think you should rephrase your answer.
@EliBendersky It is rephrased now. Check if it is correct now.
S
Suraj Jain

Static memory allocation: The compiler allocates the required memory space for a declared variable.By using the address of operator,the reserved address is obtained and this address may be assigned to a pointer variable.Since most of the declared variable have static memory,this way of assigning pointer value to a pointer variable is known as static memory allocation. memory is assigned during compilation time.

Dynamic memory allocation: It uses functions such as malloc( ) or calloc( ) to get memory dynamically.If these functions are used to get memory dynamically and the values returned by these functions are assingned to pointer variables, such assignments are known as dynamic memory allocation.memory is assined during run time.


T
Trieu Toan

Static Memory Allocation:

Variables get allocated permanently

Allocation is done before program execution

It uses the data structure called stack for implementing static allocation

Less efficient

There is no memory reusability

Dynamic Memory Allocation:

Variables get allocated only if the program unit gets active

Allocation is done during program execution

It uses the data structure called heap for implementing dynamic allocation

More efficient

There is memory reusability . Memory can be freed when not required


"Static Memory Allocation [...] It uses the data structure called stack for implementing static allocation" No, that's incorrect and misleading. please see my post for the difference between automatic and static allocation. Static memory may use the stack. This is strongly implementation dependent, and multiple strategies may be used for the same implementation. I'm not sure what you mean by "Less efficient" either. @Trieu Toan, you changed the meaning of this answer with a bad edit.
S
Suraj Jain

Difference between STATIC MEMORY ALLOCATION & DYNAMIC MEMORY ALLOCATION

Memory is allocated before the execution of the program begins (During Compilation). Memory is allocated during the execution of the program.

No memory allocation or deallocation actions are performed during Execution. Memory Bindings are established and destroyed during the Execution.

Variables remain permanently allocated. Allocated only when program unit is active.

Implemented using stacks and heaps. Implemented using data segments.

Pointer is needed to accessing variables. No need of Dynamically allocated pointers.

Faster execution than Dynamic. Slower execution than static.

More memory Space required. Less Memory space required.


static memory allocation are allocated on Stack while the Dynamic memory allocation is allocated on Heap
@UsmanKurd That's generally incorrect regarding static memory. See my answer.
R
Ritu maheswari

Static memory allocation is allocated memory before execution pf program during compile time. Dynamic memory alocation is alocated memory during execution of program at run time.


S
Suraj Jain

Static memory allocation. Memory allocated will be in stack.

int a[10];

Dynamic memory allocation. Memory allocated will be in heap.

int *a = malloc(sizeof(int) * 10);

and the latter should be freed since there is no Garbage Collector(GC) in C.

free(a);

how can static memory be allocated on the stack when memory on the stack is dynamic? Variables can get "popped off" at any time ...