Memory Allocation in C: Segments Segments
Memory Allocation in C: Segments Segments
2
Memory Allocation in C
– This push-pop operations are performed automatically
in LIFO (Last In, First Out) pattern, i.e., the variables of
the last returning
g (exiting)
( g) function is de-allocated first,
then the variables of the second to last returning
function are de-allocated and so on. For this automatic
memoryy management,
g , The size of stack-allocated
memory must always be known at compilation.
– However, in some programs, it might be necessary to
use variables / arrays with an unknown size at
compilation to provide for user-defined array size
during runtime. Under the circumstances, one must
allocate the memory dynamically during runtime,
runtime on
the ‘heap’
3
Memory Allocation in C
– C allows programmers to allocate and release heap
memory during runtime.
– Note that if one continues to allocate heap memory
space without freeing it in a program, the program
could eventually crash. So heap memory must be freed
by the programmer explicitly since heap memory is not
managed automatically like stack memory. In order to
allocate as well as free heap memory, library functions
are available which should be used inside the program.
program
4
Dynamic Memory Allocation in C
Although, C language inherently does not has any
technique to allocate memory dynamically, there are
4 library functions under "stdlib
stdlib.h
h" for dynamic
memory (i.e., heap memory) allocation.
5
malloc( )
The name malloc stands for "memory allocation". The function
malloc() reserves a block of memory (heap) of specified size and
return a pointer of type void which can be casted into pointer of
any form.
form
Syntax:
pointer_name = (cast-type*)malloc(byte-size);
Here, pointer_name is pointer of cast-type. The malloc() function
returns a pointer to an area of memory with size of byte size. If
the space is insufficient, allocation fails and returns NULL pointer.
E
Example:
l
ptr = (int*)malloc(100*sizeof(int));
This statement will allocate either 200 bytes according to size of
int 2 bytes and the ‘ptr’ points to the address of first byte of
memory. The variables then can be accessed as *ptr, *(ptr+1),
*(ptr+2), ……..….*(ptr+99). 6
calloc( )
The name calloc stands for "contiguous allocation". The only
difference between malloc() and calloc() is that, malloc()
allocates single block of memory whereas calloc() allocates
multiple blocks of memory (heap) each of same size and sets all
bytes to zero.
Syntax:
pointer_name
i t = (cast-type*)calloc(n,
( t t *) ll ( element-size);
l t i )
This statement will allocate contiguous space in memory (heap)
for an array of n elements.
E
Example:
l
ptr = (float*)calloc(25, sizeof(float);
This statement allocates contiguous space in memory for an array
of 25 elements each of size of float, i.e, 4 bytes. The variables
can be accessed by *ptr, *(ptr+1), *(ptr+2) ………….*(ptr+24).
7
free( )
Dynamically allocated memory (heap) with either calloc() or
malloc() does not get return on its own. The programmer must
use free() explicitly to release memory space.
Syntax:
free (pointer_name );
8
realloc( )
If the previously allocated memory (heap) is insufficient or more
than sufficient, then memory size can be changed using realloc().
Syntax:
realloc (pointer_name, new_size );
Here ‘pointer_name
Here, pointer name’ is reallocated with size of newsize
newsize.
9
Example-1
/* C program to find sum of n elements entered by
user. Using malloc() funcion*/
#include <stdio.h>
#include <stdlib.h>
i t main(){
int i (){
int n,i,*ptr,sum=0;
printf("Enter number of elements: ");
scanf("%d",&n);
ptr=(int*)malloc(n*sizeof(int));
if(ptr NULL){
if(ptr==NULL){
printf("Error! memory not allocated.");
exit(0);} 10
Example-1
printf("Enter elements of array: ");
for(i=0;i<n;++i)
{
scanf("%d",ptr+i);
sum+=*(ptr+i);
}
printf("Sum=%d",sum);
(p )
free(ptr);
return 0;
}
11
Example-2
/* C program to find sum of n elements entered by
user. Using calloc() funcion*/
#include <stdio.h>
#include <stdlib.h>
i t main(){
int i (){
int n,i,*ptr,sum=0;
printf("Enter number of elements: ");
scanf("%d",&n);
ptr=(int*)calloc(n,sizeof(int));
if(ptr NULL){
if(ptr==NULL){
printf("Error! memory not allocated.");
exit(0);} 12
Example-2
printf("Enter elements of array: ");
for(i=0;i<n;++i)
{
scanf("%d",ptr+i);
sum+=*(ptr+i);
}
printf("Sum=%d",sum);
(p )
free(ptr);
return 0;
}
13
Example-3
/* C program using realloc() funcion*/
#include <stdio
<stdio.h>
h>
#include <stdlib.h>
int main(){
int *ptr,i,n1,n2;
printf("Enter size of array: ");
( , )
scanf("%d",&n1);
ptr=(int*)malloc(n1*sizeof(int));
printf("Address of previously allocated memory: ");
14
Example-3
for(i=0;i<n1;++i)
printf("%u\t",ptr+i);
printf("\nEnter new size of array: ");
scanf("%d",&n2);
ptr=realloc(ptr,n2);
for(i=0;i<n2;++i)
printf("%u\t",ptr+i);
return 0;
}
15
Storage Classes
• There are four storage class specifiers
– auto
– register
i t
– static
– extern
• The storage class precedes the variable’s declaration
and instructs the compiler how the variable should be
stored
• Items declared with auto or register specifier have
local lifetimes while those declared with the static or
extern specifier have global lifetimes
16
Storage Classes
• The four storage class specifiers affect the visibility of a
variable or function, as well as its storage class
– Visibility (sometimes defined as scope of a variable)
refers to that portion of the source program in which
the variable or function can be referenced by name
• The placement of a variable or function declaration
within a source file also affects storage class and
visibilityy
• The exact meaning of each storage class specifier
depends on whether the declaration appears at the
external
t l or internal
i t l level,
l l andd whether
h th the
th item
it being
b i
declared is a variable or a function
17
Storage Classes
– Variable declarations at the external level may
only use the static or extern storage classes
– They are either definitions of variables or
references to variables defined elsewhere
– An external variable declaration that also
initializes the variable (implicitly or explicitly) is a
defining declaration:
• static int iv1 = 16; // explicit
• static
i iint iv1;
i // implicit
l 0 by
b default
d f l
• int iv2 = 20;
Once a variable is defined at the external level,, it
is visible throughout the rest of the source file in
which it appears 18
Storage Classes
• One can define a variable at the external level only once within
a source file
– If one gives the static storage class specifier, he/she can
d fi another
define th variable
i bl withith the
th same name and d the
th
static storage class specifier in a different source file;
since each static definition is visible only within its own
source file
file, no conflict occurs
• The extern storage class specifier declares a reference to a
variable defined elsewhere
– One can use an extern declaration to make visible a
definition in another source file, or to make a variable
visible above its definition in the same source file
– The variable is visible throughout the remainder of the
source file in which the declared reference occurs
19
Storage Classes
• For an extern reference to be valid, the variable it
refers to must be defined once, and only once, at the
external level
– The definition can be in any of the source files
that form the program
p g
// Source file A
#include <stdio.h>
void a (void);
void b (void);
extern int iv; // makes iv visible above its dec.
dec
20
Storage Classes
int main ()
{
iv++; // uses the above extern reference
printf ("%d\n", iv); // prints 11
a ();
return 0;
}
int iv = 10; // actual definition of iv
void a (void)
{
iv++;
printf ("%d\n", iv); // prints 12
b ();
()
}
21
Storage Classes
// Source file B
#include <stdio.h>
extern int iv; // references iv declared in Source A
void b (void)
{
iv++;
printf ("%d\n"
( %d\n , iv); // prints 13
}
• One can use any of the four storage class specifiers
or variable declarations at the internal level (the
default is auto) 22
Storage Classes
• The auto storage class specifier declares a variable
with a local lifetime
– It is visible only in the block in which it is declared
and can include initializers
• The register storage-class specifier tells the compiler
to give
i the h variable
i bl storage ini a register,
i if possible
ibl
– It speeds access time and reduces code size
– It has the same visibility as the auto variable
– If no registers are available when the compiler
encounters a register declaration, the variable is
gi en auto
given a to storage
sto age class and sto
stored
ed in memo
memory
23
Storage Classes
• A variable declared at the internal level with the
static storage class specifier has a global lifetime but
is visible only within the block in which it is declared
– Unlike auto variables, static variables keep their
values when the block is exited
– One can initialize a static variable with a constant
expression – it is initialized to 0 by default
• A variable declared with the extern storage class
specifier is a reference to a variable with the same
name defined at the external level in any of the
source files of the program
24