Author Topic: Memory Allocation in C: Compile Time vs. Run Time  (Read 3409 times)

0 Members and 1 Guest are viewing this topic.

Offline Kittu20Topic starter

  • Regular Contributor
  • *
  • Posts: 85
  • Country: in
Memory Allocation in C: Compile Time vs. Run Time
« on: September 29, 2023, 09:15:18 am »
Hello everyone,

I'm trying to wrap my head around the concept of memory allocation at compile time versus run time. My understanding is that memory for variables isn't allocated until the program runs on a PC. I belive that memory allocation happens at runtime. However, I'm confused about how memory allocation can occur at compile time when the program doesn't actually run on hardware(PC)

consider code

Code: [Select]
#include <stdio.h>
#include <stdlib.h>
 
// Global variable
int globalVar = 10;
 
 
// Static global variable
static int staticGlobalVar = 20;
 
 
int main() {
    // Local variable
    int localVar = 5;
 
 
    // Static local variable
    static int staticLocalVar = 15;
 
 
    // Dynamic memory allocation using pointers
    int *dynamicVar = (int *)malloc(sizeof(int));
 
 
    if (dynamicVar == NULL) {
        printf("Memory allocation failed.\n");
        return 1;
    }
 
 
    *dynamicVar = 25;
 
 
    // Extern variable (defined in another source file)
    extern int externVar;
 
 
    // Pointer variable
    int *pointerVar;
    pointerVar = &globalVar;
 
 
    printf("Global variable: %d\n", globalVar);
    printf("Static global variable: %d\n", staticGlobalVar);
    printf("Local variable: %d\n", localVar);
    printf("Static local variable: %d\n", staticLocalVar);
    printf("Dynamic variable: %d\n", *dynamicVar);
    printf("Extern variable: %d\n", externVar);
    printf("Pointer variable (points to globalVar): %d\n", *pointerVar);
 
 
    // Free dynamically allocated memory
    free(dynamicVar);
 
 
    return 0;
}

Could you please clarify this concept of memory allocation in C programs?
 

Online tggzzz

  • Super Contributor
  • ***
  • Posts: 19023
  • Country: gb
  • Numbers, not adjectives
    • Having fun doing more, with less
Re: Memory Allocation in C: Compile Time vs. Run Time
« Reply #1 on: September 29, 2023, 09:30:56 am »
I'm trying to wrap my head around the concept of memory allocation at compile time versus run time. My understanding is that memory for variables isn't allocated until the program runs on a PC. I belive that memory allocation happens at runtime. However, I'm confused about how memory allocation can occur at compile time when the program doesn't actually run on hardware(PC)
...
Could you please clarify this concept of memory allocation in C programs?

Yet another poor question :( See https://entertaininghacks.wordpress.com/library-2/good-questions-pique-our-interest-and-dont-waste-our-time-2/

Your code example is useless, because you have just copied it from somewhere. You need to explain what you think will happen; only after that can anybody here help you correct your misunderstanding.

Yes, we can help: this is the same for every computer language, and is well described in textbooks. Textbooks will explain this subject better than quickly scribbled responses on a forum.

Textbooks about C are widely available in India, in many of the languages used in India.

There are lies, damned lies, statistics - and ADC/DAC specs.
Glider pilot's aphorism: "there is no substitute for span". Retort: "There is a substitute: skill+imagination. But you can buy span".
Having fun doing more, with less
 
The following users thanked this post: abeyer

Offline IanB

  • Super Contributor
  • ***
  • Posts: 11726
  • Country: us
Re: Memory Allocation in C: Compile Time vs. Run Time
« Reply #2 on: September 29, 2023, 09:56:36 am »
Maybe you are familiar with the game of Monopoly? The rules of the game allocate a certain amount of money to each of the players to start with. How can the rules allocate money to the players before the game has even begun?
 

Offline Kittu20Topic starter

  • Regular Contributor
  • *
  • Posts: 85
  • Country: in
Re: Memory Allocation in C: Compile Time vs. Run Time
« Reply #3 on: September 29, 2023, 10:08:55 am »
I'm trying to wrap my head around the concept of memory allocation at compile time versus run time. My understanding is that memory for variables isn't allocated until the program runs on a PC. I belive that memory allocation happens at runtime. However, I'm confused about how memory allocation can occur at compile time when the program doesn't actually run on hardware(PC)
...
Could you please clarify this concept of memory allocation in C programs?

Yet another poor question :( See https://entertaininghacks.wordpress.com/library-2/good-questions-pique-our-interest-and-dont-waste-our-time-2/

Your code example is useless, because you have just copied it from somewhere. You need to explain what you think will happen; only after that can anybody here help you correct your misunderstanding.

Yes, we can help: this is the same for every computer language, and is well described in textbooks. Textbooks will explain this subject better than quickly scribbled responses on a forum.

Textbooks about C are widely available in India, in many of the languages used in India.

Thank you for taking the time to respond to my question, and I appreciate your feedback. In my studies of memory allocation in C programs, I've come across the concept of memory allocation happening both at compile time and run time. My confusion arises from the fact that during compilation, the program isn't actually executed on hardware. So, I'm trying to undrstand  how memory allocation can occur at compile time when there's no physical execution of the program.

The code I shared was meant to serve as an initial reference point to frame my question regarding memory allocation. Specifically, I intended to gain a better understanding of how memory allocation works in  Compile Time vs. Run Time
 

Offline Jeroen3

  • Super Contributor
  • ***
  • Posts: 4038
  • Country: nl
  • Embedded Engineer
    • jeroen3.nl
Re: Memory Allocation in C: Compile Time vs. Run Time
« Reply #4 on: September 29, 2023, 10:23:25 am »
Quote
However, I'm confused about how memory allocation can occur at compile time when the program doesn't actually run on hardware(PC)
https://devconnected.com/understanding-processes-on-linux/

On targets without OS the process is statically linked, that means that the program has explicit references of the target hardware inside.
eg: the programs knows it's .TEXT (rom) will be at 0x0000 and memory .DATA (ram) will be at 0x8000 for example.

Whatever happens next is on your runtime, and implementation of that.
https://www.gnu.org/software/libc/manual/html_node/Memory-Allocation-and-C.html

Quote
The C language supports two kinds of memory allocation through the variables in C programs:

- 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.
- Automatic allocation happens when you declare an automatic variable, such as a function argument or a local variable. The space for an automatic variable is allocated when the compound statement containing the declaration is entered, and is freed when that compound statement is exited.
In GNU C, the size of the automatic storage can be an expression that varies. In other C implementations, it must be a constant.

A third important kind of memory allocation, dynamic allocation, is not supported by C variables but is available via GNU C Library functions.

This should help you find relevant keywords to find literature.
 

Online tggzzz

  • Super Contributor
  • ***
  • Posts: 19023
  • Country: gb
  • Numbers, not adjectives
    • Having fun doing more, with less
Re: Memory Allocation in C: Compile Time vs. Run Time
« Reply #5 on: September 29, 2023, 10:36:03 am »
I'm trying to wrap my head around the concept of memory allocation at compile time versus run time. My understanding is that memory for variables isn't allocated until the program runs on a PC. I belive that memory allocation happens at runtime. However, I'm confused about how memory allocation can occur at compile time when the program doesn't actually run on hardware(PC)
...
Could you please clarify this concept of memory allocation in C programs?

Yet another poor question :( See https://entertaininghacks.wordpress.com/library-2/good-questions-pique-our-interest-and-dont-waste-our-time-2/

Your code example is useless, because you have just copied it from somewhere. You need to explain what you think will happen; only after that can anybody here help you correct your misunderstanding.

Yes, we can help: this is the same for every computer language, and is well described in textbooks. Textbooks will explain this subject better than quickly scribbled responses on a forum.

Textbooks about C are widely available in India, in many of the languages used in India.

Thank you for taking the time to respond to my question, and I appreciate your feedback. In my studies of memory allocation in C programs, I've come across the concept of memory allocation happening both at compile time and run time. My confusion arises from the fact that during compilation, the program isn't actually executed on hardware. So, I'm trying to undrstand  how memory allocation can occur at compile time when there's no physical execution of the program.

The code I shared was meant to serve as an initial reference point to frame my question regarding memory allocation. Specifically, I intended to gain a better understanding of how memory allocation works in  Compile Time vs. Run Time

Simple and correct answer: you have told the compiler to allocate memory for a variable, and the compiler has chosen where to allocate it.

You need to understand what a compiler (any compiler) is and what a compiler does. Concentrate on the correspondence between simple language statements and machine instructions.

Go to https://godbolt.org/noscript/c and type in a very short program, i.e. of similar length to the example they supply.

Use compiler directive -O0 and choose whatever machine code you are familiar with. If you aren't familiar with any, then you will struggle to understand any answer.
« Last Edit: September 29, 2023, 10:40:27 am by tggzzz »
There are lies, damned lies, statistics - and ADC/DAC specs.
Glider pilot's aphorism: "there is no substitute for span". Retort: "There is a substitute: skill+imagination. But you can buy span".
Having fun doing more, with less
 
The following users thanked this post: c64

Offline Kittu20Topic starter

  • Regular Contributor
  • *
  • Posts: 85
  • Country: in
Re: Memory Allocation in C: Compile Time vs. Run Time
« Reply #6 on: September 29, 2023, 10:47:54 am »
memory layout categories:

Text Segment:

Read-only.
Contains CPU-executable machine code instructions.

Data Segment:

Initialized Data: Holds initialized global/static variables.
Uninitialized Data: Stores uninitialized global/static variables.

Stack:

Stores local variables

Heap:

Utilized for dynamic memory allocation.
Below is a simple C code that demonstrates each of the memory layout categories 

Code: [Select]
#include <stdio.h>
#include <stdlib.h>

/* Global initialized variable in the Data Segment */
int global_initialized_var = 42;

/* Global uninitialized variable in the Data Segment (BSS) */
int global_uninitialized_var;

/* Static variable in the Data Segment */
static int static_var = 30;

void stack_example() {
    /* Local variable in the Stack */
    int local_var = 10;
    printf("Local Variable in Stack: %d\n", local_var);
}

int main() {
    /* Text Segment: CPU-executable code */
    printf("Hello from the Text Segment!\n");

    /* Accessing Initialized Data in Data Segment */
    printf("Initialized Global Variable: %d\n", global_initialized_var);

    /* Accessing Uninitialized Data in Data Segment (BSS) */
    printf("Uninitialized Global Variable: %d\n", global_uninitialized_var);

    /* Accessing Static Data in Data Segment */
    printf("Static Global Variable: %d\n", static_var);

    /* Calling a function to demonstrate Stack usage */
    stack_example();

    /* Dynamic memory allocation in the Heap */
    int *dynamic_var = (int *)malloc(sizeof(int));
    *dynamic_var = 20;
    printf("Dynamic Variable in Heap: %d\n", *dynamic_var);

    free(dynamic_var);

    return 0;
}
 
 

I have a basic understanding that memory allocation occurs when a program both compiles and runs on a PC. However, I'm trying to understand the concept of "compile-time allocation" and whether memory allocation actually happens when a program is compiled but not run.
 

Online tggzzz

  • Super Contributor
  • ***
  • Posts: 19023
  • Country: gb
  • Numbers, not adjectives
    • Having fun doing more, with less
Re: Memory Allocation in C: Compile Time vs. Run Time
« Reply #7 on: September 29, 2023, 10:54:03 am »
I have a basic understanding that memory allocation occurs when a program both compiles and runs on a PC. However, I'm trying to understand the concept of "compile-time allocation" and whether memory allocation actually happens when a program is compiled but not run.

You need to understand what a compiler does, in particular how the output corresponds to its input. Use godbolt.org (and you can even choose the language).

Short answer...

1) The compiler takes a sequence of characters and outputs a sequence of numbers.
2) During execution the processor interprets the numbers as being instructions, and executes them with the side effects defined in the processor's programming manual.

Until 2 happens, the question is meaningless.
« Last Edit: September 29, 2023, 11:20:27 am by tggzzz »
There are lies, damned lies, statistics - and ADC/DAC specs.
Glider pilot's aphorism: "there is no substitute for span". Retort: "There is a substitute: skill+imagination. But you can buy span".
Having fun doing more, with less
 

Online T3sl4co1l

  • Super Contributor
  • ***
  • Posts: 21500
  • Country: us
  • Expert, Analog Electronics, PCB Layout, EMC
    • Seven Transistor Labs
Re: Memory Allocation in C: Compile Time vs. Run Time
« Reply #8 on: September 29, 2023, 11:58:49 am »
Note that malloc() and friends, are nothing more than functions.  They may have some direct compiler support, whether for purposes of safer reasoning around freed/dangling/null pointers, or assumptions about what their return values are being used for, I don't know; but in general, they are just functions, which operate on resources already in the program at compile time.  You can write your own, if you like, overriding malloc() and free() and such (but, generally speaking, please don't; memory allocation is hard enough as it is).

The basic way a dynamic memory allocator works, is to statically declare a pool of fixed memory, and return a pointer somewhere into that.  It is entirely and explicitly up to your program to avoid stomping on anything else in that pool, which is just an ordinary array, with full ownership/usage rights by any function in the program (or any API calls made thereby).  No CPU protection is going to stop that from happening, not automatically by the compiler's normal effort at least; and give or take warnings, the compiler itself won't stop you from doing the same, either.

So, on a basic level, they're all static allocation.  You're just using one such object as a dynamic pool, and praying that malloc() and free() do what they're supposed to do in the average case, and, apparently ignoring the failure case when memory cannot be allocated or freed, not that it matters for a one-off do-nothing like this example, but, in general that's not good practice.

Now, on a hosted system, the OS can do a lot with a program, give or take how it's linked (what components are visible to the OS: modules, functions, memory objects, etc.).  It may be that memory locations are remapped when the program is loaded, so that for example no objects ever share common memory spaces, they could be on entirely different pages for example -- therefore any overrun working with one object causes a protection fault rather than stomping another otherwise-adjacent object.  Or even more fine-grained protection methods these days.  The OS can also be asked to allocate memory, in which case rather than writing all that memory into the application file, it's simply tagged as "oh by the way I need this much at label so-and-so", and the OS fills in both blanks (it allocates some of its available memory, at the address it patches in to the program in the required slots that reference that object).  And maybe this allocation happens at run-time as well as load-time, and then you have truly dynamic memory as far as the application is concerned (being able to read/write to memory locations that didn't exist at compile time -- addresses that the compiler could otherwise reasonably assume are invalid!).

Related anecdote: a long time ago, I wrote an 8086 assembly program on MS-DOS.  The resulting executable was something like 201kB, despite only ~9kB of actual code.  The ~3x 64kB graphics buffers I had declared, as uninitialized or don't-care memory, were linked into the *.EXE as all-zeroes, because I didn't pass the correct flag to the linker to tell it to let the OS allocate uninitialized memory, and frankly I didn't care at the time lol, so it dutifully wrote them into the EXE as default initialized memory, to be copied directly from hard disk, all 192k of zeroes. :)  (I could've also done dynamic allocation, where, when MS-DOS loads an application, it assumes it's going to use all available memory whether it means to or not, and allocates everything available; to use the OS for allocation, you first de-allocate the excess -- up to only as much as your program actually uses statically -- and then ask for new bits and pieces as needed.  Mind, you can go ahead and stomp on whatever memory you want, in MS-DOS -- the 8086 had no memory protection, nor when running on any later CPU either (DOS runs in real mode); it was entirely a matter of custom, and trust, that programs behaved with each other back in those days.  You could even stomp over as much of DOS itself as you wanted, if you didn't mind losing out on basic OS or even IO functionality, if you needed those last few kB of the massive 640kB RAM that was installed.  Most likely such a program ended in a JMP F000:FFF0h, i.e. to the CPU reset vector -- the easiest way for the BIOS and OS to clean up all the munged memory is to completely start over.)

A common thread through this is, how much the compiler handles, what a linker is and what it handles, and what it means to load an application and begin executing it.  And which cases are applicable where, bare-metal vs. hosted.  I'm not going into further detail on this (and I'll likely get even more things wrong in the process), but this is excellent further reading to pick up on.

Tim
Seven Transistor Labs, LLC
Electronic design, from concept to prototype.
Bringing a project to life?  Send me a message!
 
The following users thanked this post: boB, Kittu20

Offline Kittu20Topic starter

  • Regular Contributor
  • *
  • Posts: 85
  • Country: in
Re: Memory Allocation in C: Compile Time vs. Run Time
« Reply #9 on: September 29, 2023, 12:53:56 pm »

Simple and correct answer: you have told the compiler to allocate memory for a variable, and the compiler has chosen where to allocate it.

You need to understand what a compiler (any compiler) is and what a compiler does. Concentrate on the correspondence between simple language statements and machine instructions.


correct me if i am wrong in my understanding. When we compile a C program, no actual memory is allocated for variables or functions. Instead, what happens is the compiler generates instructions for the program regarding how much memory should be allocated and where it should be allocated when the program is run.

This means that the allocation of memory for variables and functions occurs during the runtime of the program, not during the compilation phase. The role of the compiler during compilation is to provide instructions and information, which manages memory allocation on the hardware, about how to allocate memory for the various variables  of  program when it is executed
 

Online T3sl4co1l

  • Super Contributor
  • ***
  • Posts: 21500
  • Country: us
  • Expert, Analog Electronics, PCB Layout, EMC
    • Seven Transistor Labs
Re: Memory Allocation in C: Compile Time vs. Run Time
« Reply #10 on: September 29, 2023, 01:01:41 pm »

Simple and correct answer: you have told the compiler to allocate memory for a variable, and the compiler has chosen where to allocate it.

You need to understand what a compiler (any compiler) is and what a compiler does. Concentrate on the correspondence between simple language statements and machine instructions.


correct me if i am wrong in my understanding. When we compile a C program, no actual memory is allocated for variables or functions. Instead, what happens is the compiler generates instructions for the program regarding how much memory should be allocated and where it should be allocated when the program is run.

This means that the allocation of memory for variables and functions occurs during the runtime of the program, not during the compilation phase. The role of the compiler during compilation is to provide instructions and information, which manages memory allocation on the hardware, about how to allocate memory for the various variables  of  program when it is executed

What variables?

Statics and globals are allocated, and you will indeed find them in the EXE or whatever via hexdump or binutils.  (Uninitialized/zeroed may not, as most OSs and linkers, or platform support libraries, handle them more efficiently.)

Anything on the stack, doesn't exist anywhere in the program at all, until such time as the function performs the allocation on entry.  Whether a given system has enough stack space available for such an allocation, is up to you (give or take if the compiler is aware of it, and does something about it; offhand, I think avr-gcc for example does not, you can happily allocate more on the stack than extant RAM and it doesn't care).  Likewise, it ceases to exist (semantically) on exiting the function so must not be referred to outside the function (e.g. a function can erroneously return a pointer to a local variable; and sometimes you'll actually get away with it..!)

Tim
Seven Transistor Labs, LLC
Electronic design, from concept to prototype.
Bringing a project to life?  Send me a message!
 

Online tggzzz

  • Super Contributor
  • ***
  • Posts: 19023
  • Country: gb
  • Numbers, not adjectives
    • Having fun doing more, with less
Re: Memory Allocation in C: Compile Time vs. Run Time
« Reply #11 on: September 29, 2023, 02:25:51 pm »

Simple and correct answer: you have told the compiler to allocate memory for a variable, and the compiler has chosen where to allocate it.

You need to understand what a compiler (any compiler) is and what a compiler does. Concentrate on the correspondence between simple language statements and machine instructions.


correct me if i am wrong in my understanding. When we compile a C program, no actual memory is allocated for variables or functions. Instead, what happens is the compiler generates instructions for the program regarding how much memory should be allocated and where it should be allocated when the program is run.

This means that the allocation of memory for variables and functions occurs during the runtime of the program, not during the compilation phase. The role of the compiler during compilation is to provide instructions and information, which manages memory allocation on the hardware, about how to allocate memory for the various variables  of  program when it is executed

Why don't you have a look at the output of a compiler at godbolt.org? There you will see what the compiler has done.

The compiler "knows" how an instruction will manipulate memory (and registers) when the instruction is executed. During compilation, the compiler internally keeps track of what manipulations need to be done, and outputs the series of instructions necessary - those are merely a sequence of numbers.

The exact manipulations can vary considerably, depending on the language, the compiler, the processor, and especially the compiler optimisation level. Sometimes they will involve memory, sometimes - particularly with higher optimisation levels - they will be purely register operations.

At runtime the processor interprets the series of instructions.

Example source C code:
Code: [Select]
extern int put( int );

int aStatic = 12;

int foo( int x ) {
    int aLocal = 34;
    return x + aLocal - aStatic;
}

void baz() {
    int result = foo( 56 );
    put(result & 0xff);
}

using x86-64 clang (trunk) -O0
Code: [Select]
# Compilation provided by Compiler Explorer at https://godbolt.org/
foo:                                    # @foo
        push    rbp
        mov     rbp, rsp
        mov     dword ptr [rbp - 4], edi
        mov     dword ptr [rbp - 8], 34
        mov     eax, dword ptr [rbp - 4]
        add     eax, dword ptr [rbp - 8]
        sub     eax, dword ptr [rip + aStatic]
        pop     rbp
        ret
baz:                                    # @baz
        push    rbp
        mov     rbp, rsp
        sub     rsp, 16
        mov     edi, 56
        call    foo
        mov     dword ptr [rbp - 4], eax
        mov     edi, dword ptr [rbp - 4]
        and     edi, 255
        call    put@PLT
        add     rsp, 16
        pop     rbp
        ret
aStatic:
        .long   12                              # 0xc
where you can see statically allocated memory, push/pop operations, and subroutine calls/returns.

But when optimised using -O3
Code: [Select]
# Compilation provided by Compiler Explorer at https://godbolt.org/
foo:                                    # @foo
        sub     edi, dword ptr [rip + aStatic]
        lea     eax, [rdi + 34]
        ret
baz:                                    # @baz
        mov     eax, 90
        sub     eax, dword ptr [rip + aStatic]
        movzx   edi, al
        jmp     put@PLT                         # TAILCALL
aStatic:
        .long   12                              # 0xc
the compiler has done all the addition and subtraction arithemetic operations at compile time, kept values in registers, and avoided subroutine calls.
There are lies, damned lies, statistics - and ADC/DAC specs.
Glider pilot's aphorism: "there is no substitute for span". Retort: "There is a substitute: skill+imagination. But you can buy span".
Having fun doing more, with less
 

Offline MikeK

  • Super Contributor
  • ***
  • Posts: 1314
  • Country: us
Re: Memory Allocation in C: Compile Time vs. Run Time
« Reply #12 on: September 29, 2023, 05:03:41 pm »
Why don't you have a look at the output of a compiler at godbolt.org? There you will see what the compiler has done.

This is cool.  Thanks.
 

Online tggzzz

  • Super Contributor
  • ***
  • Posts: 19023
  • Country: gb
  • Numbers, not adjectives
    • Having fun doing more, with less
Re: Memory Allocation in C: Compile Time vs. Run Time
« Reply #13 on: September 29, 2023, 06:01:57 pm »
Why don't you have a look at the output of a compiler at godbolt.org? There you will see what the compiler has done.

This is cool.  Thanks.

At least one person is paying attention :)

I wonder if the OP will?
There are lies, damned lies, statistics - and ADC/DAC specs.
Glider pilot's aphorism: "there is no substitute for span". Retort: "There is a substitute: skill+imagination. But you can buy span".
Having fun doing more, with less
 

Offline IanB

  • Super Contributor
  • ***
  • Posts: 11726
  • Country: us
Re: Memory Allocation in C: Compile Time vs. Run Time
« Reply #14 on: September 29, 2023, 09:06:07 pm »
I'm trying to wrap my head around the concept of memory allocation at compile time versus run time.

OK

Quote
My understanding is that memory for variables isn't allocated until the program runs on a PC.

This understanding is wrong. You are mistaken.

Quote
I believe that memory allocation happens at runtime.

It can happen at runtime, but it doesn't have to be this way. For example, in Fortran 77 allocation never happens at runtime--the possibility is not even available in the language.

Quote
However, I'm confused about how memory allocation can occur at compile time when the program doesn't actually run on hardware(PC)

You are confused because you are starting from a position of incorrect understanding.

It might be helpful to know what your situation is. Are you a student? If so, are you a student of computer science or computer engineering, or of some other discipline? In any event, you will want to look at basic textbooks describing how computers work. You need that understanding before you think about compilers (which is an advanced topic). If you try to think about compilers before you think about computing machines, you will naturally get confused.

So what you need to first understand is how a computer works at the machine level. What is the basic design of all modern computer systems? Once you understand how memory is laid out, and how the CPU can read and write memory locations by memory address, then you can understand how the compiler can allocate certain memory addresses in advance to store data (variables). The compiler can even pre-load those addresses with initial data.

(This is glossing over the roles of a linker and loader, and relocating programs in memory, but relocation does not need to happen on the most primitive machines.)
 

Online SiliconWizard

  • Super Contributor
  • ***
  • Posts: 14043
  • Country: fr
Re: Memory Allocation in C: Compile Time vs. Run Time
« Reply #15 on: September 29, 2023, 09:46:56 pm »
static vs. dynamic allocation would make more sense than "compile time" vs. "run time" allocation IMHO.

Formally speaking, until some executable runs, nothing is happening, so is there any allocation to speak of? Also formally speaking, static "allocation" happens (or maybe more correctly, is "prepared" or "layouted" ) more at link-time than compile-time, if that matters. But also note that even static allocation has a run-time effect, as - at least on hosted environments - it is usually prepared before the main() function is called. (For instance, initialized data copied - typically .data segment(s) - and non-initialized data zeroed out - typically .bss segment.)

Regarding dynamic allocation, it can take various forms. The most common people have in mind is allocation on the "heap". But allocation on the stack is also dynamic. So, uh, yeah.
« Last Edit: September 29, 2023, 09:49:00 pm by SiliconWizard »
 
The following users thanked this post: T3sl4co1l, magic, Kittu20

Offline Kittu20Topic starter

  • Regular Contributor
  • *
  • Posts: 85
  • Country: in
Re: Memory Allocation in C: Compile Time vs. Run Time
« Reply #16 on: September 30, 2023, 01:41:57 am »

I wonder if the OP will?

I tried the link, but it produced assembly code. I'm not familiar with assembly language, so I didn't comment on it. I know it's good to learn assembly language, but at this time, I am focusing on learning C language only
 

Offline Kittu20Topic starter

  • Regular Contributor
  • *
  • Posts: 85
  • Country: in
Re: Memory Allocation in C: Compile Time vs. Run Time
« Reply #17 on: September 30, 2023, 02:08:00 am »
static vs. dynamic allocation would make more sense than "compile time" vs. "run time" allocation IMHO.


This link say https://www.geeksforgeeks.org/difference-between-static-and-dynamic-memory-allocation-in-c/  that static memory is allocated at compile time.

Suppose we've written a program that includes a global variable. When we compile this code on  Windows PC, does the compiler allocate memory for the global variable.?

Or Instead,  does it write instructions into the program's executable file that allocate memory for the global variable when it run on PC?
 

Offline IanB

  • Super Contributor
  • ***
  • Posts: 11726
  • Country: us
Re: Memory Allocation in C: Compile Time vs. Run Time
« Reply #18 on: September 30, 2023, 02:52:21 am »
I tried the link, but it produced assembly code. I'm not familiar with assembly language, so I didn't comment on it. I know it's good to learn assembly language, but at this time, I am focusing on learning C language only

In order to understand the answer to the question you are asking, you must learn something about computing machines and how they work, and that includes understanding something about how memory is organized within a computer. You cannot reasonably expect to learn the C language without doing this, or you will become completely confused when you try to understand arrays and pointer arithmetic. If you are unwilling to do this, then you should pick another language to learn that does not have pointers, such as C#, Java or Python.

This link say https://www.geeksforgeeks.org/difference-between-static-and-dynamic-memory-allocation-in-c/  that static memory is allocated at compile time.

Suppose we've written a program that includes a global variable. When we compile this code on  Windows PC, does the compiler allocate memory for the global variable.?

Yes.

Quote
Or Instead,  does it write instructions into the program's executable file that allocate memory for the global variable when it run on PC?

No. What you are missing is that a program's executable can contain both instructions and data. The data part is where variables can be stored.

The definition of static memory is that it is allocated by the compiler into a data area before the program starts running, and remains accessible until the program ends. But you will not understand this until you learn about machines, machine code, and assembly language. Without that, you must simply accept it as given.

By the way, when I was growing up, 14 year old students learning computer science would learn about the basic structure of a computer (and assembler language) before ever learning about a high level language. This is how fundamental it was considered.
« Last Edit: September 30, 2023, 03:01:16 am by IanB »
 
The following users thanked this post: Kittu20

Offline Kittu20Topic starter

  • Regular Contributor
  • *
  • Posts: 85
  • Country: in
Re: Memory Allocation in C: Compile Time vs. Run Time
« Reply #19 on: September 30, 2023, 03:07:08 am »

This link say https://www.geeksforgeeks.org/difference-between-static-and-dynamic-memory-allocation-in-c/  that static memory is allocated at compile time.

Suppose we've written a program that includes a global variable. When we compile this code on  Windows PC, does the compiler allocate memory for the global variable.?

Yes.


so Global and static variables are allocated memory during compilation, and the compiler  allocate their memory addresses in the program's data segment. For example, let's say globalVar is located at memory address 0x1000. For example, let's say staticVar is located at memory address 0x2000. 

 

Offline magic

  • Super Contributor
  • ***
  • Posts: 6715
  • Country: pl
Re: Memory Allocation in C: Compile Time vs. Run Time
« Reply #20 on: September 30, 2023, 05:13:02 am »
Quote
My understanding is that memory for variables isn't allocated until the program runs on a PC.
This understanding is wrong. You are mistaken.
It really depends on what you mean by those words.

I'm with SiliconWizard - memory is allocated when you run a program and deallocated when you stop it to run a different one.
Technically, what the complier linker allocates statically are addresses.


The only case of truly static allocation of memory is when you design a computer which always runs one particular software :D
 

Offline IanB

  • Super Contributor
  • ***
  • Posts: 11726
  • Country: us
Re: Memory Allocation in C: Compile Time vs. Run Time
« Reply #21 on: September 30, 2023, 05:31:49 am »
This is semantics, and it depends on the meaning of the word allocate. To allocate can mean to select in advance, or to earmark, how something will be used. Hence my post in Reply #2 above. The rules of Monopoly allocate, or earmark, a certain amount of money to each of the players at the start of the game. This happens in the abstract, before any game has actually started.

In the same way, the compiler allocates, or earmarks, a certain amount of memory to store static variables. This happens before the program has even been loaded.
 

Offline magic

  • Super Contributor
  • ***
  • Posts: 6715
  • Country: pl
Re: Memory Allocation in C: Compile Time vs. Run Time
« Reply #22 on: September 30, 2023, 06:09:08 am »
My point is, you can't really say that it's wrong to state that memory is allocated at runtime.
In a way, almost all memory is allocated dynamically in a multi tasking OS.
Hell knows what the OP really meant.
 

Offline metebalci

  • Frequent Contributor
  • **
  • Posts: 423
  • Country: ch
Re: Memory Allocation in C: Compile Time vs. Run Time
« Reply #23 on: September 30, 2023, 07:15:17 am »
This is semantics, and it depends on the meaning of the word allocate. To allocate can mean to select in advance, or to earmark, how something will be used. Hence my post in Reply #2 above. The rules of Monopoly allocate, or earmark, a certain amount of money to each of the players at the start of the game. This happens in the abstract, before any game has actually started.

In the same way, the compiler allocates, or earmarks, a certain amount of memory to store static variables. This happens before the program has even been loaded.

I think I agree with this point and I think it is because of use or definition of allocate (warning: English is not my first language). For allocation, Oxford (dict) says "an amount of money, space, etc. that is given to somebody for a particular purpose". In that senses, I dont like using allocation with compile time. Merriam Webster, in addition to above meaning, says "to set apart or earmark : DESIGNATE", and in this sense, it makes sense. Naturally it should be obvious what is meant in context of compilation and runtime, but still it may cause some ambiguity.

By the way, when program is compiled in IBM mainframes in 60s using punch cards etc., maybe something different was going on, and maybe this usage is at least partially an historical artifact.
 

Online tggzzz

  • Super Contributor
  • ***
  • Posts: 19023
  • Country: gb
  • Numbers, not adjectives
    • Having fun doing more, with less
Re: Memory Allocation in C: Compile Time vs. Run Time
« Reply #24 on: September 30, 2023, 07:37:10 am »

I wonder if the OP will?

I tried the link, but it produced assembly code. I'm not familiar with assembly language, so I didn't comment on it. I know it's good to learn assembly language, but at this time, I am focusing on learning C language only

You will fail to understand C or C++ unless you understand (1) how a processor operates and (2) interacts with its memory.

Without that understanding any programs you write will be cargo cult programming, which might work sometimes but which will "randomly" fail occasionally. That is especially true with multicore processors and cache memory hierarchies.

I suggest you stick with a language that is designed to hide the hardware from you, e.g. Python.
There are lies, damned lies, statistics - and ADC/DAC specs.
Glider pilot's aphorism: "there is no substitute for span". Retort: "There is a substitute: skill+imagination. But you can buy span".
Having fun doing more, with less
 


Share me

Digg  Facebook  SlashDot  Delicious  Technorati  Twitter  Google  Yahoo
Smf