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

0 Members and 1 Guest are viewing this topic.

Offline Kittu20Topic starter

  • Regular Contributor
  • *
  • Posts: 96
  • Country: in
Re: Memory Allocation in C: Compile Time vs. Run Time
« Reply #25 on: September 30, 2023, 08:02:00 am »

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

My understanding is that Computer hardware reads binary instructions from program memory to perform tasks. Program memory stores the instructions that make up a program, and these instructions guide the hardware in executing specific tasks. Data memory, on the other hand, is where the values of variables are stored.

When we declare a global or static variable in code, the compiler assigns a memory address to that variable, which serves as the location in data memory where the variable's (global or static ) value will be stored during program execution. 
 

Offline DiTBho

  • Super Contributor
  • ***
  • Posts: 3915
  • Country: gb
Re: Memory Allocation in C: Compile Time vs. Run Time
« Reply #26 on: September 30, 2023, 10:01:15 am »
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

yup, which however can be absolute, or relative, depending on the ISA of the CPU, the machine-layer of the compiler, in turn conditioned by user flags or directives passed from the source.

e.g. when you want "relocatable code", addresses are all relative, except memory mapped devices and shared memory, which need absolute addressing.

Variables inside a function, can have two approches
1) assigned to registers (RISC approach)
2) pushed on the stack (stack-machines(1) and CISC approach)

Putting something on the stack is equivalent to making it relative addressing, based on the stack pointer.



(1) an educational example is the ijvm (integer java(-like) virtual machine) created by prof Andrew S. Tanenbaum in the early 2000s. In the book that describes it almost all the examples are in ijvm assembly, very easy to follow.
The opposite of courage is not cowardice, it is conformity. Even a dead fish can go with the flow
 

Offline tggzzz

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

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

My understanding is that Computer hardware reads binary instructions from program memory to perform tasks. Program memory stores the instructions that make up a program, and these instructions guide the hardware in executing specific tasks. Data memory, on the other hand, is where the values of variables are stored.

When we declare a global or static variable in code, the compiler assigns a memory address to that variable, which serves as the location in data memory where the variable's (global or static ) value will be stored during program execution.

That is simplistic, especially with higher compiler optimisation levels. My example illustrated that.

Once you understand how a processor and memory works, then it will be much easier for you to understand why C has keywords "const", "volatile", "restrict", and why aliasing is an issue - especially in multicore processors. Understanding why the keywords are there is, unfortunately, only the start: you also need to understand what they don't mean/guarantee.

Caution: many experienced programmers think they understand what those qualifiers do, but actually they don't. In general C is full of "undefined behaviour" (UB) traps, which can easily cause surprises up to and including entire programs being reduced to a couple of instructions - or demons flying out of your nose (a.k.a. nasal demons).
« Last Edit: September 30, 2023, 10:43:43 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: Kittu20

Offline DavidAlfa

  • Super Contributor
  • ***
  • Posts: 5907
  • Country: es
Re: Memory Allocation in C: Compile Time vs. Run Time
« Reply #28 on: September 30, 2023, 11:10:44 am »
Your question mainly asks the difference between static, stack and dynamic memory allocation.
I understand some concepts are hard to get by, by others like this one only take some reading!
There're thousands of sites explaining this. Have you even tried to google it?

https://www.geeksforgeeks.org/static-and-dynamic-memory-allocation-in-c/
https://craftofcoding.wordpress.com/2015/12/07/memory-in-c-the-stack-the-heap-and-static/

« Last Edit: September 30, 2023, 11:14:54 am by DavidAlfa »
Hantek DSO2x1x            Drive        FAQ          DON'T BUY HANTEK! (Aka HALF-MADE)
Stm32 Soldering FW      Forum      Github      Donate
 
The following users thanked this post: Kittu20

Offline Kittu20Topic starter

  • Regular Contributor
  • *
  • Posts: 96
  • Country: in
Re: Memory Allocation in C: Compile Time vs. Run Time
« Reply #29 on: September 30, 2023, 11:29:14 am »

Once you understand how a processor and memory works, then it will be much easier for you to understand

The CPU is responsible for executing program instructions stored in program memory. It fetches, decodes, and executes these instructions (refrence 8051 archtecture), using registers and other components to manipulate data and perform operations. Program memory holds the program instructions,
 

Offline tggzzz

  • Super Contributor
  • ***
  • Posts: 19497
  • Country: gb
  • Numbers, not adjectives
    • Having fun doing more, with less
Re: Memory Allocation in C: Compile Time vs. Run Time
« Reply #30 on: September 30, 2023, 01:06:06 pm »

Once you understand how a processor and memory works, then it will be much easier for you to understand

The CPU is responsible for executing program instructions stored in program memory. It fetches, decodes, and executes these instructions (refrence 8051 archtecture), using registers and other components to manipulate data and perform operations. Program memory holds the program instructions,

That is true for all computers.
It is dangerously simplistic for many, e.g. ARM, x86. Remember, you have previously started threads on large/complex systems, not 8051-class systems https://www.eevblog.com/forum/microcontrollers/larger-and-more-complex-embedded-systems/msg5072092/#msg5072092
Although it is 25 years too late(!), C has tried to keep up with processors+memory by finally defining a memory model.

The 8051 has, I believe, four different types of memory - and programmers will have to specify which type to use using mechanisms that are outside the C standard. Some compilers add another three types of memory, again not standard C. https://en.wikipedia.org/wiki/Intel_8051#Memory_architecture

If you want to program an 8051 you must understand the hardware architecture, and that can't be done without understanding assembly code.
« Last Edit: September 30, 2023, 01:15:37 pm 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
 

Offline tggzzz

  • Super Contributor
  • ***
  • Posts: 19497
  • Country: gb
  • Numbers, not adjectives
    • Having fun doing more, with less
Re: Memory Allocation in C: Compile Time vs. Run Time
« Reply #31 on: September 30, 2023, 01:11:12 pm »
Your question mainly asks the difference between static, stack and dynamic memory allocation.
I understand some concepts are hard to get by, by others like this one only take some reading!
There're thousands of sites explaining this. Have you even tried to google it?

Yes, unlikely, and it has already been suggested :(

The OP has admitted to using ChatGPT to write his questions.

I've asked  questions because I'm genuinely curious and eager to understand a particular concept. English is not my first language, so I used AI to  format my question. However, I know that ChatGPT can't replace the real-time work experience and expertise that individuals in the industry have earned through their careers.
« Last Edit: September 30, 2023, 01:13:12 pm 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
 

Offline Kittu20Topic starter

  • Regular Contributor
  • *
  • Posts: 96
  • Country: in
Re: Memory Allocation in C: Compile Time vs. Run Time
« Reply #32 on: September 30, 2023, 02:52:53 pm »
Your question mainly asks the difference between static, stack and dynamic memory allocation.
I understand some concepts are hard to get by, by others like this one only take some reading!
There're thousands of sites explaining this. Have you even tried to google it?

Yes, unlikely, and it has already been suggested :(

The OP has admitted to using ChatGPT to write his questions.


I'd like to clarify that DavidAlfa mention what i need to ask.  Just to clarify, Now I don't use AI to draft questions; I simply ask questions in my own version of English.

There're thousands of sites explaining this. Have you even tried to google it?
I've done quite a bit of research on this topic, and I've also included a reference link in my previous post (#17) FYI
« Last Edit: September 30, 2023, 02:54:46 pm by Kittu20 »
 

Offline tggzzz

  • Super Contributor
  • ***
  • Posts: 19497
  • Country: gb
  • Numbers, not adjectives
    • Having fun doing more, with less
Re: Memory Allocation in C: Compile Time vs. Run Time
« Reply #33 on: September 30, 2023, 03:14:22 pm »
Your question mainly asks the difference between static, stack and dynamic memory allocation.
I understand some concepts are hard to get by, by others like this one only take some reading!
There're thousands of sites explaining this. Have you even tried to google it?

Yes, unlikely, and it has already been suggested :(

The OP has admitted to using ChatGPT to write his questions.


I'd like to clarify that DavidAlfa mention what i need to ask.  Just to clarify, Now I don't use AI to draft questions; I simply ask questions in my own version of English.

There're thousands of sites explaining this. Have you even tried to google it?
I've done quite a bit of research on this topic, and I've also included a reference link in my previous post (#17) FYI

Get a decent textbook in your native language. Too many sites are poor recapitulations of what is on other sites by people that aren't experts. Soon ChatGPT generated sites will make that even worse.

I see no problem in formulating your question in your native language and using google translate to mutate it into English.
« Last Edit: September 30, 2023, 03:15:59 pm 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: abeyer

Offline DavidAlfa

  • Super Contributor
  • ***
  • Posts: 5907
  • Country: es
Re: Memory Allocation in C: Compile Time vs. Run Time
« Reply #34 on: September 30, 2023, 09:29:09 pm »
I also understand the struggle when you don't know the term you're searching for!

For example in mechanical devices, I need some sort of metal thing holding two pieces together, preventing them from slippping when rotating.
It's unlikely that searching that in Google leads to a woodruff key or DIN 6885 parallel keys, or at least not fast.

Same for computing/sorting algorithms, chemical reactions, hand tools, etc, etc, you're f*** up unless you know the name  :-DD.

« Last Edit: September 30, 2023, 09:31:59 pm by DavidAlfa »
Hantek DSO2x1x            Drive        FAQ          DON'T BUY HANTEK! (Aka HALF-MADE)
Stm32 Soldering FW      Forum      Github      Donate
 

Online ejeffrey

  • Super Contributor
  • ***
  • Posts: 3719
  • Country: us
Re: Memory Allocation in C: Compile Time vs. Run Time
« Reply #35 on: October 02, 2023, 01:55:59 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

I'm going to go somewhat against what people have said that you "need" to understand how processors work at a machine level to understand C.  However you are asking a question that goes beyond the scope of just the language.  All C requires is that the implementation make global and static variable lifetime for the entire duration of the program.  How and where that happens is fundamentally a machine question and if you won't take "it just does" for an answer you are going to need to learn about how actual machines operate.

Basically what happens when you launch a program on almost anything that constitutes an operating system is that a certain amount of memory is set aside for the program's execution.  Then some of all of that memory is initialized based on the contents of the program executable image.  Then the operating system jumps to a defined address within that space.  Exactly how this process works is different from system to system, DOS COM files work differently than Linux dynamically linked executables, but those are still the steps.

That memory generally includes both code and data although the OS may or may not make a distinction between them.

So when you declare a global variable in C, the compiler (including the linker) put information into the executable image to make sure space for the variable is included when the program is loaded and initialized as needed.

In the simplest case where the OS just loads a blob of data to a fixed address, that would just be including the variables initial value in the blob and making sure references to it use the right address.  That's a common way for this to work but not the only way.  The only thing that is required is that the variables are allocated before main() starts, and exist until after main exits.

« Last Edit: October 02, 2023, 02:06:42 am by ejeffrey »
 

Offline Nominal Animal

  • Super Contributor
  • ***
  • Posts: 6260
  • Country: fi
    • My home page and email address
Re: Memory Allocation in C: Compile Time vs. Run Time
« Reply #36 on: October 02, 2023, 09:49:06 am »
One of the key concepts to understand before one can understand memory allocation is address spaces.

As an example, let's take 8051.  It is a good example, because it has several address spaces:
  • Internal RAM, with 128 directly accessible bytes, of which 32 bytes form four register windows for R0-R7 registers, and 16 bytes form 128 individually directly accessible one-bit registers; and up to 128 special function registers that include the A/ACC and B accumulators
  • Up to 65536 bytes of read-only program memory
  • Up to 65536 bytes of read-write data memory, of which the first 256 bytes can be accessed via their address in R0 or R1 register, and the rest only via the address in DPTR register
The key is that knowing an address, say 5th byte or address 4, may refer to any address space.  (Even AMD64/x86-64 supports at least three concurrent separate address spaces: the default one, and two others specified via FS and GS segment register selectors.)

Each address space can be split into many different logical parts.  For example, most current 8051 implementations have 256 bytes of internal RAM, where the upper 128 bytes is typically used for stack.  If we use the ELF object file format terms, we call human-decided logical address space parts sections.

Typical microcontroller code and applications running under real OSes have one or two sections in read-only program memory: .text, and possibly .rodata; and up to four sections in the data memory: initialized data in .data, uninitialized or zero-initialized data in .bss, an unnamed section for stack, and optionally an unnamed section for heap.  On some microcontrollers like AVRs, and under older operating systems like DOS, the heap and stack occupied the same section (address range), with heap addresses growing up or in increasing addresses, and stack growing down with decreasing addresses.
Under fully featured operating systems, there are additional syscalls (brk/sbrk, mmap) to request additional accessible address ranges, if needed at run time.

Thus, if we look at a typical 8051 or other microcontroller code, static and global variables' addresses are fixed at link time, and so is the address ranges used for dynamic allocation.  If the dynamic allocations always occur with specific sizes in specific order, the dynamically obtained addresses will always be the same.  (Under desktop and server OSes, the address spaces can actually be randomized, but that is an intentional security measure.)



As a real-world analog, think of each address space available on your microcontroller as a bookshelf with movable dividers with labels.
At compile time, the compiler generates machine code, but instead of putting code and static variables and global variables directly in the bookshelf, it puts them in boxes (sections).
At link time, these boxes are arranged on the bookshelf according to the 'linker script', or link-time directions.  (In the past, linkers were separate tools one would execute in ones build scripts, but nowadays we tend to let the compiler call the linker directly.)
As I mentioned earlier, on a microcontroller, an additional box may be set up for stack, and another for heap, for run-time allocations.

In a very real sense, the heap allocator and deallocator functions –– in C, typically malloc() and free() –– put and remove additional sub-boxes into the heap box at run time; essentially just reserving small sub-chunks of address space within the pre-reserved region.

Thus, the concept of memory allocation 'at compile time or at run time' is itself wrong: the address ranges are set at link time –– which can be at build time when linking statically, or at run time when linking dynamically, and often both; but for microcontrollers with fixed address spaces is at the end of the build ––, but additional ranges can be requested from the operating system if running under one; and if a 'heap' range is set up or requestable from the operating system, it can be managed at run time like books from a library.  Some specific addresses can also be set at compile time, for example peripheral device I/O addresses and such.  It is a hierarchy that starts in the code at compile time, and extends all through to run time; not either-or.

Therefore, the correct answer is that some special addresses can be fixed in the code and thus set at compile time; function addresses and static and global variable addresses are set at link time; sections/regions like stack are set at link time; heap region is initialized at link time but more or additional heap regions can be requested from the OS if running under one at run time; and one or more contiguous parts within the heap region or regions can be allocated and deallocated at run time.  Hierarchy of things, not either-or.
 
The following users thanked this post: Kittu20

Offline tggzzz

  • Super Contributor
  • ***
  • Posts: 19497
  • Country: gb
  • Numbers, not adjectives
    • Having fun doing more, with less
Re: Memory Allocation in C: Compile Time vs. Run Time
« Reply #37 on: October 02, 2023, 09:59:42 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

I'm going to go somewhat against what people have said that you "need" to understand how processors work at a machine level to understand C.  However you are asking a question that goes beyond the scope of just the language.  All C requires is that the implementation make global and static variable lifetime for the entire duration of the program.  How and where that happens is fundamentally a machine question and if you won't take "it just does" for an answer you are going to need to learn about how actual machines operate.

Some aspects of C really cannot be understood without understanding how processors+memory work. Even "experts" have had problems with that concept, as demonstrated by Hans Boehm (of the conservative GC fame) needing to write "Threads cannot be implemented as a library" in exhaustive detail http://hboehm.info/misc_slides/pldi05_threads.pdf

The OP is targeting the 8051. Given how hostile that is to plain-vanilla C without extensions, good luck getting C code to work on that without understanding the 8051's arhitectural features.
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 DiTBho

  • Super Contributor
  • ***
  • Posts: 3915
  • Country: gb
Re: Memory Allocation in C: Compile Time vs. Run Time
« Reply #38 on: October 02, 2023, 11:46:20 am »
Intel 51 is one of the architecture that you d best program in assembly.
The opposite of courage is not cowardice, it is conformity. Even a dead fish can go with the flow
 

Offline tggzzz

  • Super Contributor
  • ***
  • Posts: 19497
  • Country: gb
  • Numbers, not adjectives
    • Having fun doing more, with less
Re: Memory Allocation in C: Compile Time vs. Run Time
« Reply #39 on: October 02, 2023, 11:55:44 am »
Intel 51 is one of the architecture that you d best program in assembly.

That's my impression, but some of the PICs look worse.

In either case I would want to verify that a compiler had translated my code into sane machine code.
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 Kittu20Topic starter

  • Regular Contributor
  • *
  • Posts: 96
  • Country: in
Re: Memory Allocation in C: Compile Time vs. Run Time
« Reply #40 on: October 02, 2023, 03:25:36 pm »
AT89S52 microcontroller executes programs from its flash memory by fetching, decoding, and executing instructions stored in flash memory. It uses a program counter to keep track of the next instruction to execute, allowing it to run the program sequentially.

The opcode is the part of an instruction that defines the operation to be performed (e.g., 'MOV' for move), while the operand specifies the data or location involved (e.g., '#5' for a constant). Machine code is the binary representation of these instructions stored in the microcontroller's flash memory, which the CPU directly executes.

SFR (Special Function Register) addresses, as detailed in Datasheet Table 1 on Page 5, are memory-mapped locations that provide access to specific functions and configurations. Microcontroller programmers utilize these SFR addresses to configure I/O pins, set up timer/counters, control interrupts, and interact with other hardware modules.

I can find SFR address information in the header file.

https://www.keil.com/dd/docs/c51/atmel/regx51.h

I think the compiler assigns these addresses at compile time, so when it generates the executable file , they should be hard-coded. they remain the same when the program is running on the microcontroller.

 

Online ejeffrey

  • Super Contributor
  • ***
  • Posts: 3719
  • Country: us
Re: Memory Allocation in C: Compile Time vs. Run Time
« Reply #41 on: October 02, 2023, 06:14:30 pm »
Some aspects of C really cannot be understood without understanding how processors+memory work. Even "experts" have had problems with that concept, as demonstrated by Hans Boehm (of the conservative GC fame) needing to write "Threads cannot be implemented as a library" in exhaustive detail http://hboehm.info/misc_slides/pldi05_threads.pdf

I look at that in exactly the opposite way.  Understanding the machine doesn't really help you here.  Actually it can and does lead you astray, since the guarantees that the hardware makes don't matter if the compiler doesn't expose them to the programmer in a usable fashion.  For instance, even recently I have argued against to people still using volatile for multi-thread synchronization that they shouldn't do that because it is incorrect.  They usually claim something like "I only care about x86 and this code is correct under x86 memory order guarantees."  That would be fine if they were using assembly, but it's not correct when writing C (or C++) because the C memory model is not the same as the architectural memory model.

C and C++ needed a memory model to enable multi-threaded programming, and knowledge of the underlying architecture and it's memory model *was not* sufficient to produce correct multi-threaded code without it.

Quote
The OP is targeting the 8051. Given how hostile that is to plain-vanilla C without extensions, good luck getting C code to work on that without understanding the 8051's arhitectural features.

That's a fair point, although at that point you have to debate whether you are programming C or "a C-like language"
 

Offline SiliconWizard

  • Super Contributor
  • ***
  • Posts: 14471
  • Country: fr
Re: Memory Allocation in C: Compile Time vs. Run Time
« Reply #42 on: October 02, 2023, 07:29:02 pm »
Some aspects of C really cannot be understood without understanding how processors+memory work. Even "experts" have had problems with that concept, as demonstrated by Hans Boehm (of the conservative GC fame) needing to write "Threads cannot be implemented as a library" in exhaustive detail http://hboehm.info/misc_slides/pldi05_threads.pdf

I look at that in exactly the opposite way.  Understanding the machine doesn't really help you here.  Actually it can and does lead you astray,

I actually agree with both of you on different levels. The two are not mutually exclusive, contrrary to how it may look at first thought.

- I agree with that fact that understanding the low-level aspects of the hardware is a definite requirement for really understanding C.
- But I do agree that with this knowledge must come the appropriate level of abstraction when you design your code, and this level entirely depends on what exactly you are designing.

C is precisely this spot - that's often been considered a sweet spot, at least until now - between low-level and high-level, and as such requires a good command of both.

If you want much lower level than C, use assembly. Conversely, if the high-level aspects of C are not high-level enough to you or for implementing a given piece of software - at least according to your standards - use another language as well.
 

Offline SiliconWizard

  • Super Contributor
  • ***
  • Posts: 14471
  • Country: fr
Re: Memory Allocation in C: Compile Time vs. Run Time
« Reply #43 on: October 02, 2023, 07:30:43 pm »
Intel 51 is one of the architecture that you d best program in assembly.

It's not pretty but I've used C for 8051-based MCUs (like the Cypress FX stuff) using SDCC and it was perfectly usable once you got familiar with the limitations.
 

Offline DiTBho

  • Super Contributor
  • ***
  • Posts: 3915
  • Country: gb
Re: Memory Allocation in C: Compile Time vs. Run Time
« Reply #44 on: October 03, 2023, 10:43:54 am »
Intel 51 is one of the architecture that you d best program in assembly.

It's not pretty but I've used C for 8051-based MCUs (like the Cypress FX stuff) using SDCC and it was perfectly usable once you got familiar with the limitations.

perfectly usable ... sure, even a colleague of mine also spoke well about it, then I noticed that he wasn't even aware of the various problems that the 8032 and 8051 have, he had taken a ready-made template project found on a GitHub, modified it, and "oh, look, it can be programmed, perfectly usable"

A bloody Genius  :o :o :o
The opposite of courage is not cowardice, it is conformity. Even a dead fish can go with the flow
 

Offline tggzzz

  • Super Contributor
  • ***
  • Posts: 19497
  • Country: gb
  • Numbers, not adjectives
    • Having fun doing more, with less
Re: Memory Allocation in C: Compile Time vs. Run Time
« Reply #45 on: October 03, 2023, 07:04:29 pm »
Some aspects of C really cannot be understood without understanding how processors+memory work. Even "experts" have had problems with that concept, as demonstrated by Hans Boehm (of the conservative GC fame) needing to write "Threads cannot be implemented as a library" in exhaustive detail http://hboehm.info/misc_slides/pldi05_threads.pdf

I look at that in exactly the opposite way.  Understanding the machine doesn't really help you here.  Actually it can and does lead you astray, since the guarantees that the hardware makes don't matter if the compiler doesn't expose them to the programmer in a usable fashion.  For instance, even recently I have argued against to people still using volatile for multi-thread synchronization that they shouldn't do that because it is incorrect.  They usually claim something like "I only care about x86 and this code is correct under x86 memory order guarantees."  That would be fine if they were using assembly, but it's not correct when writing C (or C++) because the C memory model is not the same as the architectural memory model.

We agree, except that my attitude is that not understanding the hardware allowed people to be blind to C's manifest deficiencies w.r.t. memory consistency.

I say "manifest" because K&R C was explicit that the language did not address threading, and that that was the responsibility of libraries. Subsequent generations of programmers didn't realise that, and blithely ignored the issue. Hence the need for Boehm's paper.

Instead the C committee spent years amusing themselves about whether it should be possible or impossible to "throw away  constness"; there are solid arguments for and against each.

That lack of decision made me decide that C was becoming part of the problem rather than part of the solution.

Others finally seem to agree, and soon Rust will supplant C in the same way that COBOL has been supplanted by Java and other languages.

Quote
C and C++ needed a memory model to enable multi-threaded programming, and knowledge of the underlying architecture and it's memory model *was not* sufficient to produce correct multi-threaded code without it.

Scandalously C took quarter of a century to gain a memory model, even though is was obviously mandatory - as per Java!

Whether C's memory model and compilers' implementation is sufficient and correct is an open question in my mind. It is a very complex subtle topic; even Java got it subtly wrong and had to correct it after a decade of experience.

Quote
Quote
The OP is targeting the 8051. Given how hostile that is to plain-vanilla C without extensions, good luck getting C code to work on that without understanding the 8051's arhitectural features.

That's a fair point, although at that point you have to debate whether you are programming C or "a C-like language"

Yup :)
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 tggzzz

  • Super Contributor
  • ***
  • Posts: 19497
  • Country: gb
  • Numbers, not adjectives
    • Having fun doing more, with less
Re: Memory Allocation in C: Compile Time vs. Run Time
« Reply #46 on: October 03, 2023, 07:11:21 pm »
If you want much lower level than C, use assembly. Conversely, if the high-level aspects of C are not high-level enough to you or for implementing a given piece of software - at least according to your standards - use another language as well.

In the 1990s C.reached a point where it needed to decide whether to be a general purpose high level programming language, or a special purpose close to the silicon language. Either is good and acceptable.

It failed to decide, tried to be both, and failed at both.

People have moved on to Java for HLL purposes, and are moving on to Rust for close to silicon purposes. Good! About time too :)
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 SL4P

  • Super Contributor
  • ***
  • Posts: 2318
  • Country: au
  • There's more value if you figure it out yourself!
Re: Memory Allocation in C: Compile Time vs. Run Time
« Reply #47 on: October 03, 2023, 10:34:04 pm »
You can be allocated a parking space, but never use it,
You can be assigned a parking space, but never use it,

There is a subtle difference.
Allocation means a space (unknown) has been noted, will be given ‘assigned to you when you need it.. it will be assigned to you.

Until it’s been ‘assigned’, other vehicles can use it, and you’ll never know about it,
Don't ask a question if you aren't willing to listen to the answer.
 

Offline c64

  • Frequent Contributor
  • **
  • Posts: 298
  • Country: au
Re: Memory Allocation in C: Compile Time vs. Run Time
« Reply #48 on: October 03, 2023, 11:25:23 pm »
Short answer to the original question.

Global variables

If your target has OS, it will be OS who allocate memory. Before your main() is started.

If you are on bare metal, there is no allocation needed. You already own all the memory available.

Locals and dynamic

These are allocated by your running application. Usually on stack/heap
 

Offline c64

  • Frequent Contributor
  • **
  • Posts: 298
  • Country: au
Re: Memory Allocation in C: Compile Time vs. Run Time
« Reply #49 on: October 03, 2023, 11:37:49 pm »
Compiler or linker do not allocate anything. They calculate how much memory your application will require for all the global variables, and there they will be (variable x will be at address 0, variable y at address 8, etc.) when the application is running on your target device
 


Share me

Digg  Facebook  SlashDot  Delicious  Technorati  Twitter  Google  Yahoo
Smf