Storage Class and Dynamic Memory Allocation

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 6

Storage Classes in C

Storage classes in C are used to determine the lifetime, visibility, memory location, and initial value of
a variable. There are four types of storage classes in C

 Automatic
 External
 Static
 Register

Storage Storage Default


Scope Lifetime
Classes Place Value
Garbage
auto RAM Local Within function
Value
Till the end of the main program Maybe declared
extern RAM Zero Global
anywhere in the program
Till the end of the main program, Retains value
static RAM Zero Local
between multiple functions call
Garbage
register Register Local Within the function
Value

Automatic

 Automatic variables are allocated memory automatically at runtime.


 The visibility of the automatic variables is limited to the block in which they are defined.
 The scope of the automatic variables is limited to the block in which they are defined.
 The automatic variables are initialized to garbage by default.
 The memory assigned to automatic variables gets freed upon exiting from the block.
 The keyword used for defining automatic variables is auto.
 Every local variable is automatic in C by default.

Example 1
#include <stdio.h>  
main()  
{  
int a = 10,i;   
printf("%d ",++a);  
{  
int a = 20;   
for (i=0;i<3;i++)  
{  
printf("%d ",a); // 20 will be printed 3 times since it is the local value of a  
}  
}  
printf("%d ",a); // 11 will be printed since the scope of a = 20 is ended.   
}  

Output: 11 20 20 20 11

Static

 The variables defined as static specifier can hold their value between the multiple function calls.
 Static local variables are visible only to the function or the block in which they are defined.
 A same static variable can be declared many times but can be assigned at only one time.
 Default initial value of the static integral variable is 0 otherwise null.
 The visibility of the static global variable is limited to the file in which it has declared.
 The keyword used to define static variable is static.

Example 3
#include<stdio.h>  
void sum()  
{  
static int a = 10;  
static int b = 24;   
printf("%d %d \n",a,b);  
a++;   
b++;  
}  
main()  
{  
int i;  
for(i = 0; i< 3; i++)  
{  
sum(); // The static variables holds their value between multiple function calls.    
}  
}  

Output:

10 24
11 25
12 26

Register

 The variables defined as the register is allocated the memory into the CPU registers depending upon
the size of the memory remaining in the CPU.
 We cannot dereference the register variables, i.e., we cannot use & operator for the register variable.
 The access time of the register variables is faster than the automatic variables.
 The initial default value of the register local variables is 0.
 The register keyword is used for the variable which should be stored in the CPU register. However, it is
compiler’s choice whether or not; the variables can be stored in the register.
 We can store pointers into the register, i.e., a register can store the address of a variable.
 Static variables cannot be stored into the register since we cannot use more than one storage specifier
for the same variable.

Example 3
#include <stdio.h>  
main()  
{  
register int a; // variable a is allocated memory in the CPU register. The initial default value of a is 0.   
printf("%d",a);  
}  

Output:

0
External

 The external storage class is used to tell the compiler that the variable defined as extern is declared
with an external linkage elsewhere in the program.
 The variables declared as extern are not allocated any memory. It is only declaration and intended to
specify that the variable is declared elsewhere in the program.
 The default initial value of external integral type is 0 otherwise null.
 We can only initialize the extern variable globally, i.e., we can not initialize the external variable within
any block or method.
 An external variable can be declared many times but can be initialized at only once.
 If a variable is declared as external then the compiler searches for that variable to be initialized
somewhere in the program which may be extern or static. If it is not, then the compiler will show an
error.

Example 4
#include <stdio.h>  
main()  
{  
extern int a; // Compiler will search here for a variable a defined and initialized somewhere in the pogram 
or not.   
printf("%d",a);  
}  
int a = 20;  

Output

20

Dynamic memory allocation in C

The concept of dynamic memory allocation in c language enables the C programmer to allocate
memory at runtime. Dynamic memory allocation in c language is possible by 4 functions of stdlib.h
header file.

1. malloc()
2. calloc()
3. realloc()
4. free()

Difference between static memory allocation and dynamic memory allocation:

static memory allocation dynamic memory allocation


Memory is allocated at compile time. Memory is allocated at run time.
Memory can't be increased while executing Memory can be increased while executing
program. program.
Used in array. Used in linked list.

Now let's have a quick look at the methods used for dynamic memory allocation.

malloc() Allocates single block of requested memory.


calloc() Allocates multiple block of requested memory.
realloc() Reallocates the memory occupied by malloc() or calloc() functions.
free() Frees the dynamically allocated memory.
malloc() function in C

The malloc() function allocates single block of requested memory.

It doesn't initialize memory at execution time, so it has garbage value initially.

It returns NULL if memory is not sufficient.

The syntax of malloc() function is given below:

ptr=(cast-type*)malloc(byte-size)  

Let's see the example of malloc() function.

#include<stdio.h>  
#include<stdlib.h>  
main(){  
  int n,i,*ptr,sum=0;    
    printf("Enter number of elements: ");    
    scanf("%d",&n);    
    ptr=(int*)malloc(n*sizeof(int));  //memory allocated using malloc    
    if(ptr==NULL)                         
    {    
        printf("Sorry! unable to allocate memory");    
        exit(0);    
    }    
    printf("Enter elements of array: ");    
    for(i=0;i<n;++i)    
    {    
        scanf("%d",ptr+i);    
        sum+=*(ptr+i);    
    }    
    printf("Sum=%d",sum);    
    free(ptr);     
return 0;  
}    

Output:

Enter elements of array: 3


Enter elements of array: 10
10
10
Sum=30

calloc() function in C

The calloc() function allocates multiple block of requested memory.

It initially initialize all bytes to zero.

It returns NULL if memory is not sufficient.

The syntax of calloc() function is given below:


ptr=(cast-type*)calloc(number, byte-size)  

realloc() function in C

If memory is not sufficient for malloc() or calloc(), you can reallocate the memory by realloc()
function. In short, it changes the memory size.

Let's see the syntax of realloc() function.

ptr=realloc(ptr, new-size)  

free() function in C

The memory occupied by malloc() or calloc() functions must be released by calling free() function.
Otherwise, it will consume memory until program exit.

Let's see the syntax of free() function.

free(ptr)  

What are Pointers?

A pointer is a variable whose value is the address of another variable, i.e., direct address of the
memory location. Like any variable or constant, one must declare a pointer before using it to store any
variable address. The general form of a pointer variable declaration is −

type *var-name;

Example:

int *ip; /* pointer to an integer */


double *dp; /* pointer to a double */
float *fp; /* pointer to a float */
char *ch /* pointer to a character */

Initialize a pointer

After declaring a pointer, we initialize it like standard variables with a variable address. If pointers are
not uninitialized and used in the program, the results are unpredictable and potentially disastrous.

To get the address of a variable, we use the ampersand (&)operator, placed before the name of a
variable whose address we need. Pointer initialization is done with the following syntax.

pointer = &variable;

A simple program for pointer illustration is given below:

#include <stdio.h>
int main()
{
int a=10; //variable declaration
int *p; //pointer variable declaration
p=&a; //store address of variable a in pointer p
printf("Address stored in a variable p is:%x\n",p); //accessing the address
printf("Value stored in a variable p is:%d\n",*p); //accessing the value
return 0;
}

Operators for pointer:


Operator Meaning
Serves 2 purpose

* 1. Declaration of a pointer
2. Returns the value of the referenced variable

Serves only 1 purpose


&
 Returns the address of a variable

Advantages of Pointers

 Pointers are useful for accessing memory locations.


 Pointers provide an efficient way for accessing the elements of an array structure.
 Pointers are used for dynamic memory allocation as well as de-allocation.
 Pointers are used to form complex data structures such as linked list, graph, tree, etc.

Disadvantages of Pointers

 Pointers are a little complex to understand.


 Pointers can lead to various errors such as segmentation faults or can access a memory location which
is not required at all.
 If an incorrect value is provided to a pointer, it may cause memory corruption.
 Pointers are also responsible for memory leakage.
 Pointers are comparatively slower than that of the variables.
 Programmers find it very difficult to work with the pointers; therefore it is programmer's responsibility
to manipulate a pointer carefully.

You might also like