Reputation: 31
I have this code example in c from an introductory Embedded system course quiz :
#include <stdlib.h>
#include <stdint.h>
//cross-compiled for MSP432 with cortex-m0plus
int main() {
int * l2;
return 0;
}
I want to know the memory segment ,sub-segment, permissions and lifetime of *l2 in memory.
What I understand is that the pointer l2 is going to be allocated in the stack sub-segment first then because it's uninitialized it's going to get a garbage value which is in this case any value it finds in the stack; I assumed it was in the .text or .const with a static lifetime and none of these answers were right, so am I missing something here ?
Edit:
After I passed the quiz without solving this point correctly, the solution table says it's in the heap with indefinite lifetime. what i got from this answer is that : because a pointer itself is stored in stack and the object it points to is uninitialized (it's not auto or static), it's stored in the heap.. I guess ??
Upvotes: 1
Views: 204
Reputation: 123548
The value stored in l2
is indeterminate - it can even be a trap representation. The l2
object itself has auto
storage duration and its lifetime is limited to the lifetime of the enclosing function. What that translates into in terms of memory segment depends on the specific implementation.
You can’t say anything about the value of *l2
, unless your specific implementation documents exactly how uninitialized pointers are handled.
Upvotes: 1
Reputation: 67751
It depends on the implementation.
Usually as it is local automatic variable it will be located on the stack. Its lifetime is the same as lifetime of the main
function. It can be only accessed from the main function.
But in real life as you do not do anything with it, it will be just removed by the compiler as not needed even if if you compile it with no optimizations https://godbolt.org/z/1Y6W5j . In this case its location is "nowhere"
Objects can be also kept in the registers and not be placed in the memory https://godbolt.org/z/8nWxxz
Most modern C implementations place code in the .text
segment, initialized static storage location variables in the .data
segment, not initialized static storage location variables in the .bss
segment and read only data in the .rodata
segment . You may have plenty other memory segments in your program - but there are so many options. You can also have your own segments and place objects there.
Stack and heap location are 100% implementation defined.
Upvotes: 2