In: Computer Science
Explain the difference in the C memory model between global and local variables. How is each allocated and accessed?
There are 4 sections in memory: data, heap, stack, and
code.
In C, There are 2 kind of variables that get created.. The local
and the global variables.. The local variables are created on the
stack, while the global variables are created in the data section.
The global variables can be accessed from anywhere in the coe and
their values can be changed as well by any piece of code.. While
the local variables are accessible only in the scope of the
function, which is containing the variable declaration..
Here is an example:
int myGlobal = 5; void func1() { int temp = 1; // This is a local variable only accessible in func1 printf("Temp: %d\n", temp); // we can change the value of temp as well here. } int main() { // We can read the value of global variable here, as well as change it. printf("Global: %d\n", myGlobal); myGlobal = 10; printf("Global: %d\n", myGlobal); func1(); // At this point, our call to func1 is completed, and thus temp variable // is not anymore present. }
************************************************** Thanks for your question. We try our best to help you with detailed answers, But in any case, if you need any modification or have a query/issue with respect to above answer, Please ask that in the comment section. We will surely try to address your query ASAP and resolve the issue.
Please consider providing a thumbs up to this question if it helps you. by Doing that, You will help other students, who are facing similar issue.