Where are pointers and global variables stored in C? Are they saved in the memory, heap or stack?
Global variables are stored in the data section.
Global variables are stored in the data segment of memory. Local variables are stored in a stack in memory.
A pointer is a variable that contains the address where something lives. They aren't directly related to each other in any way. A pointer variable can be in global or local scope and can also point to a variable that is in global, local, or no scope (as if it were coming off of the heap or addressing some DIO lines).
Pointers are used for file handling. Pointers are used to allocate memory dynamically. In C++, a pointer declared to a base class could access the object of a derived class. However, a pointer to a derived class cannot access the object of a base class.
Global variables can be in a couple places, depending on how they're set up - for example, const
globals may be in a read-only section of the executable. "Normal" globals are in a read-write section of the executable. They're not on the heap or the stack at all. Pointers are just a type of variable, so they can be wherever you want them to be (on the heap if you malloc()
them, on the stack if they're local variables, or in the data section if they're global).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With