1. Scope:
Scope specifies accessibility of a data object in different part of program in other words part of a program, where a data object can be accessed by it’s name. We’ll see scope of different variables in further sections.
2. Storage Class:
Storage class in C determines the part of a program memory where storage of a data object is allocated. Sometime it also defines life of the object i.e. how long the storage will exist. There are four storage classes defined by ANSI in C:
- auto
- register
- static
- extern (Global)
2.1 Automatic variable (auto storage class):
Keyword: auto (optional)
Generally automatic variables are declared in the starting of program blocks (code enclosed within curly braces i.e. { }), but some compiler also supports declaration of automatic variable anywhere inside block although it not recommended because it affects readability of a program. They can be declared using auto keyword but it is optional. Any variable declared in a block is treated as automatic until unless any other storage class is specified. Function parameters are also considered as automatic variables.
Life:
Storage of an automatic variable is allocated at the time of its declaration and released upon exit of the block in which it is declared. Every time a block is entered, all automatic variables are initialized to its default value specified at their declaration. If any automatic variable is not initialized, it carries some junk data. It is always recommended to initialize every automatic variable at its declaration.
Scope:
The scope of automatic variable is local to the block including all the nested blocks inside that block. This is the reason why they are also called local variable. An automatic variable can’t be directly accessed (using its name specified at declaration) from outside of its declaration block. Indirectly (using mediator) they can be accessed by other blocks using pointers, function parameters, and global variables during its life time. If there is an automatic variable with same name in outer block or in global declaration then every access made on the variable will refer to the variable declared in current execution block.
Storage:
As discussed above, storage for an automatic variable is allocated at its declaration, and is freed upon exit of its declaration block. Allocation of automatic variable is done in the stack segment within the frame of function containing the block.
Example:
#include<stdio.h>
void myRoutine(int* param)
{ /* Block0 starts from here */
/* param is auto (local) variable to this block */
printf("Block0 Value of param:%d\n",*param);
*param=123; /* modified the value */
}/* Block 0 ends here */
int main()
{/* Block 1 starts from here */
int u_var=25; /* u_var is an auto variable and it’s life starts from here, declaration “auto int u_var;” is also OK */
int in_var=10; /* in_var is also an auto variable, it cannot be access before this point */
{/* Block 2 starts from here */
int in_var=5; /* in_var is local variable to block 2 it will omit in_var of block1*/
int bl2_var=20;
/* u_var is accessible in this block too but in_var is not accessible in this block because there is another variable declared in this block with same name */
printf("Block2: in_var=%d, u_var=%d\n",in_var,u_var);
} /* block2 ends here */
/* bl2_var and in_var of block2 are not accessible here */
myRoutine(&in_var); /* in_var is passed through parameter it will be accessible in block0 through param */
printf("Block2: in_var=%d, u_var=%d\n",in_var,u_var);
return 0;
} /* block1 ends here, therefore life of u_var and in_var ends here */
Output:
Block2: in_var=5, u_var=25
Block0 Value of param:10
Block2: in_var=123, u_var=25
2.2 Register Variables (register storage class):
Keyword: register
We know that a computer has primary storage such as CPU registers, cache and RAM to store run time instructions and data. In these, CPU has fastest access to its registers and slowest to RAM. Primarily automatic variables are stored in RAM and compiler determines what variable is to be stored at what time in CPU registers. C provides register variables so that a programmer can instruct to compiler that this variable should be allocated to CPU register. Generally variables which are used repeatedly or whose access time is critical may be declared as register variable. Thus register variables provide a limited control over efficiency of program execution.
Life:
Similar to automatic variable, register variables are always part of program block they are allocated to a CPU register at the time of its declaration and deallocated upon exit of the block. In every aspect register variables are similar to automatic variables except their storage location.
Scope:
Scope rules are similar to automatic variables.
Storage:
Every register variable is likely to be stored in CPU register but it is not an obligation for CPU to do this. In case CPU doesn’t have sufficient free registers, it can refuse this request. Since every register variable occupies a register, so it is always recommended minimal use of register variable. Excess use of register variable may degrade CPU performance.
Example:
#include<stdio.h>
int main()
{
register int reg_var=25; /* reg_var is a register variable */
int aut_var=10; /* aut_var is an auto variable */
/*
Porgram code here:
*/
return 0;
}
2.3 External Variable (global variables):
Keyword: extern
Register and automatic variables have limited scope (block in which they are declared) and limited life. External variables are accessible from any block and it remains for the entire execution of program. External variables are also called as global variables. Usually declaration of global variable is always kept out side of any block and at the beginning of a source file, and it doesn’t require extern keyword. If the program is in several source files, and a variable is defined in let say file1.c and used in file2.c and file3.c then the extern keyword must be used in file2.c and file3.c.
If a global variable is to be accessed from multiple files then usual practice is to collect extern declarations of variables and functions in a separate header file (.h file) then include by using #include directive. External variables may be initialized in declarations just as automatic variables; however, the initializers must be constant expressions. The initialization is done only once at compile time, i.e. when memory is allocated for the variables. In general, it is always recommended to avoid using external variables as they destroy the concept of a function as a independent module.
There may be occasions when the use of an external variable significantly simplifies the implementation of an algorithm. Suffice it to say that external variables should be used rarely and with caution. Two global variables with same name can not exist in a C program.
Life:
Memory for such variables is allocated when the program begins execution, and remains allocated until the program terminates.
Scope:
The scope of external variables is global, i.e. the entire source code in the file following the declarations. All functions following the declaration may access the external variable by using its name. However, if a local variable having the same name is declared within a function, references to the name will access the local variable. It is also accessible from any other source file.
Storage:
Memory of an uninitialized global variable is allocated in bss section since bss section is initialized to zero so every uninitialized global variable becomes zero initialized. Initialized global variable is allocated in data section.
Example:
File1.c
#include<stdio.h>
int GlobalVar1=20;
int GlobalVar2=10;
int main()
{
printf(“GlobalVar=%d\n”,GlobalVar1);
return 0;
}
File2.c
extern int GlobalVar1; /* GlobalVar1 of File1.c is accessible any where in File2.c */
void foo(void)
{
extern int GlobalVar2; /* GlobalVar2 of File1.c is accessible only inside function foo */
printf(“GlobalVar1=%d, GlobalVar2=%d\n”,GlobalVar1,GlobalVar2);
}
2.4 Static Variable (static storage class):
Keyword: static
Similar to global variables, static storage class provides a life time over the entire program, however it also provides a way to limit the scope of such variables. These variables are declared with static keyword. Declaration of static variable may be kept out side of any block as well in side a block.
Similar to global variables if static variables are left uninitialized by programmer, they are initialized to zero by compiler. Static automatic variables continue to exist even after the block in which they are defined terminates. Thus, the value of a static variable in a function is retained between repeated function calls to the same function i.e. initialization of a static variable in side a block is ignored after first execution of the block. A static variable can be accessed only in the file where it is defined.
Life:
Similar to global variables memory for such variables is allocated when the program begins execution, and remains allocated until the program terminates.
Scope:
If a static variable is defined inside a block, the scope of static variables becomes identical to that of automatic variables, i.e. it is local to the block in which it is defined; however, the storage allocated becomes permanent for the duration of the program. If it is defined out side of block, the scope of static variables becomes similar to that of global variables the only limitation is that they can not be accessed from any other file.
Storage:
Memory of an uninitialized static variable is allocated in bss section and initialized static variable is allocated in data section; the initializer must be constant expression, and initialization is done only once at compile time when memory is allocated for the static variable.
Example:
#include<stdio.h>
static int StatVar1=20; /* StatVar1 is accessible from anywhere in File1.c */
void foo(void)
{
static int StatVar2=10; /* StatVar2 is accessible only inside function foo */
printf(“StatVar2=%d\n”,StatVar2);
StatVar2 +=10;
}
int main()
{
printf(“StatVar1=%d\n”,StatVar1);
foo();
foo();
return 0;
}
Out Put:
StatVar1=20
StatVar2=10
StatVar2=20
3. Memory Allocation:
In C, memory allocation for variables is done by two mean:
3.1 Static Allocation:
This type of allocation is done for global and static variables. Such type of memory is reserved by compiler at compilation and allocated when the program is loaded in to computer memory and freed only when program exits. Compiler reserves such memory in form of bss and data sections.
3.2 Automatic Allocation:
This type of allocation happens for an automatic variables such as a function argument or a local variable. The space for an automatic variable is allocated when the compound statement containing the declaration is entered, and is freed when that compound statement is exited. Automatic allocation takes place in the stack segment only.
3.3 Limitation of static and automatic allocation:
For above two types of memory allocation, size of block to be allocated is defined by compiler and it depends on the type of the variable. They also have limitation of statically defined size of allocation particularly for array. However, in many situations, it is not clear how much memory the program will actually need. If too much memory is allocated and then not used, there is a waste of memory. If not enough memory is allocated, the program will not work for larger inputs.
3.4 Dynamic Memory Allocation:
A program can be more flexible, if during execution, it could allocate required memory when needed and free up the memory when it is no more needed. Allocation of memory during execution is called dynamic memory allocation. C provides library functions to allocate and free up memory dynamically during program execution. Dynamic memory is allocated on the heap by the system.
Dynamic memory allocation also has limits. If memory is repeatedly allocated and not freed, the system will run out of memory.
3.5 Standard C Library functions for dynamic memory allocation:
malloc()
Description:
Allocates specified number of bytes from heap. It returns address of the first byte of allocated memory. The return address doesn’t point to any specific data type, so we need to typecast it to the type of destination pointer. It returns NULL pointer if allocation fails.
Prototype:
void * malloc(size_t nByte);
nByte: Number of bytes to be allocated.
Return Value:
Address of first byte of allocated block or NULL if allocation fails.
Usage:
char *Ptr=NULL;
Ptr = (char *) malloc(10*sizeof(char)); /* allocates memory for 10 characters */
calloc()
Description:
calloc is very similar to malloc in its operation except it initializes all elements of the allocated memory to zero and it has two parameters. It allocates requested number of fixed size elements. Size of element is fixed in an allocation and is specified by a parameter.
Prototype:
void* calloc(size_t nElem, size_t elemSize) ;
nElem: Number of elements to allocate
elemSize: Size of each elements
Return Value:
Address of first byte of allocated block or NULL if allocation fails.
Usage:
char *Ptr=NULL;
Ptr = (char *) calloc(10, sizeof(char)); /* allocates memory for 10 characters */
realloc()
Desciption:
Some time we may need to change size of pre-allocated block. realloc() serves this requirement. The
realloc
function changes the size of a given block. If requested size of block is larger than the existing block then there may be situation where space after the existing block is in use then realloc() allocates a new block of requested size and copies data of old block to new location and frees the old block. Prototye:
void * realloc(void *CurrBlock, size_t NewSize);
CurrBlock: Address of existing memory block
NewSize: New size requested for the block.
Return Value:
Address of first byte of reallocated block or NULL if reallocation fails.
Usage:
char *pCh1=NULL, *pCH2=NULL;
pCh1=(char*)malloc(10);
pCh2=(char*)realloc(pCh, 20);
Notes:
realloc() changes the size of the memory block pointed to by pCh1 to 20 bytes. The contents will be unchanged to the minimum of the old and new sizes; newly allocated memory will be uninitialized. If pCh1 passed in realloc() is NULL, the call is equivalent to malloc(20); if requested size is equal to zero, the call is equivalent to free(pCh1). Unless pCh1 is NULL, it must have been returned by an earlier call to malloc(), calloc() or realloc(). If the area pointed by pCh1 was moved, a free(pCh1) is done by calloc. You can not pass address of an array for resizing.
free()
Description:
Releases a memory block dynamically allocated by malloc(), calloc(), and realloc() and adds it to free list of heap.
Prototye:
void free(void *MemBlock);
MemBlock: Address of memory block to be released
Return Value:
None.
Usage:
char *pCh1=NULL;
pCh1=(char*)malloc(10*sizeof(char)); /* allocate memory for 10 characters */
/* code to use block pointed by pCh1 */
free(pCh1);
pCh1=NULL;
/* no more usage of block pointed by pCh1 */