Location of a dereferenced uninitialized pointer in memory?

199 Views Asked by At

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 ??

2

There are 2 best solutions below

0
On

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.

0
On

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.