This answer is for the beginners or others who may face the same problem to clarify the problem and to explain how did I figured it out.
A stack is a section in the memory where local variables are stored. Local variables are the non-static variables defined inside a function. Another usage of the stack is to store the address of the latest executed command before jumping to another function or interrupt service routine (ISR) so that CPU knows from where should it continue when it finishes executing the ISR or the other function. When a local variable is defined, its value is saved in the stack. As soon as the function finishes executing, this local variable doesn't exist anymore and its address in the stack is free to be used.
The problem as @the_busybee pointed out was because of defining a local array and assigning its address (which is in the stack) to a globally defined pointer. Then the global pointer itself is saved in .bss
memory section while the address it is pointing at is in the stack.
Now how did I figured out
- After posting the question I was trying to edit it to make it more clear. This helps you clarifying your thoughts (like the rubber duck debugging method. Many times I found the answer to the question just by trying to formulate it in a clear way.
- Then I was thinking that
why does the stack pointer point to the address of a globally defined variable
.
- To make sure that this assumption is correct I checked the address where the global variable is defined. It was
0x20003F4
. Then I checked the address saved in the globally defined pointer. It was 0x20006FD0
.
- I thought then, what if this pointed-at address is a part of the stack area? I checked the
.map
file and found that .stack
starts at address 0x20006c00
and has the size of 0x400
. This means that 0x20006FD0
is indeed part of the stack.
- Then I remembered that I defined the array pointed at by the global pointer locally in a function.
- At this point I saw the comment of the_busybee and cancelled editing the question and start writing this answer :)
I hope this answer helps