-
Difference between variable declaration globally and locally
over 9 years ago
-
over 9 years ago
In C the local variables are allocated memory in the stack, where as the global data is not kept in the stack. The major reason behind keeping the locally declared variables in a stack is to prevent malicious scripts from consuming memory space unnecessarily.
As global data is not stored in the stack you can declare your "arr[1000][1800]" and it will be allocated the memory space if this much memory is available. But if you try to do the same in a function, the stack size limit(which depends on platform and is generally around 8 mb) does not let your array get the required memory and thus result in "Segmentation fault".
One way to get rid of this is to increase the stack limit, and you can do this by executing the following in a shell :-
ulimit -s 500000 #i.e (change your stack limit to something near about 500 mb or as per your requirement)
I hope this solves your doubt.
-
over 9 years ago
First of all let me specify what are Global and Local Variables
- Global variable defines one block of space of a fixed size. The space is allocated once, when your program is started (part of the exec operation), and is never freed.
- The space for an local variable is allocated when the compound statement containing the declaration is entered, and is freed when that compound statement is executed.
For Local Variable:
Variables that you define inside functions are allocated on the stack. That means that the associated memory is cleaned up (the stack is "popped") when the function exits.For Global Variable:
Variables defined in global scope are allocated in a data segment (or, generally, a memory space requested from the operating system) that exists for the lifetime of the process.
Additionally
Memory allocated using malloc is allocated from a heap and remains allocated until explicitly released using free.
Note that a modern OS may well provide address space requested by a program, but not physically back that address space with RAM until the memory (or a portion of the memory often called a page) is physically accessed.
-
about 5 years ago
Global variables are declared outside any function.
They can be accessed (used) on any function in the program.
Scope Within the whole programme.
Local variables are declared inside a function.
It can be used only inside that function.
Scope Within the function where it is declared.
Note: It is possible to have local variables with the same name in different functions. -
3 Answer(s)