0% found this document useful (0 votes)
49 views

FCP 5 Pointers

The document discusses pointers in C programming. It defines pointers as variables that store memory addresses rather than values. Pointers allow accessing and modifying variables indirectly through memory addresses. The document explains how to declare pointer variables, assign memory addresses to pointers using the address-of operator "&", and dereference pointers using the indirection operator "*" to access the value stored at that memory address. It provides examples of pointer declarations, assignments, and usage in code snippets.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
49 views

FCP 5 Pointers

The document discusses pointers in C programming. It defines pointers as variables that store memory addresses rather than values. Pointers allow accessing and modifying variables indirectly through memory addresses. The document explains how to declare pointer variables, assign memory addresses to pointers using the address-of operator "&", and dereference pointers using the indirection operator "*" to access the value stored at that memory address. It provides examples of pointer declarations, assignments, and usage in code snippets.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 119

Recall

 Function
 Recursion
 Write a C program to find sum of first n natural numbers
using recursion. Note: Positive integers are known as
natural number i.e. 1, 2, 3....n
#include <stdio.h>
int sum(int n);
int main()
{
int num,add;
printf("Enter a positive integer:\n");
scanf("%d",&num);
add=sum(num);
printf("sum=%d",add);
}
int sum(int n){
if(n==0)
return n;
else
return n+sum(n-1); /*self call to function sum() */
}
=sum(5)
=5+sum(4)
=5+4+sum(3)
=5+4+3+sum(2)
=5+4+3+2+sum(1)
=5+4+3+2+1+sum(0)
=5+4+3+2+1+0
=5+4+3+2+1
=5+4+3+3
=5+4+6
=5+10
=15
Pointers
Introduction
 First of all, it is variable, just like other variables you
studied.
– so it has type, storage etc.
 A pointer is a variable that represents the location (rather
than the value) of a data item.
 Difference: it can only store the address (rather than the
value) of a data item.
 They have a number of useful applications.
– Enables us to access a variable that is defined
outside the function.
– Can be used to pass information back and forth
between a function and its reference point.
– More efficient in handling data tables.
– Reduces the length and complexity of a program.
– Sometimes also increases the execution speed.
Basic Concept
 In memory, every stored data item occupies one or more
contiguous memory cells.
– The number of memory cells required to store a
data item depends on its type (char, int, double, etc.).
1 1.2 C

 Whenever we declare a variable, the system allocates


memory location(s) to hold the value of the variable.
– Since every byte in memory has a unique address,
this location will also have its own (unique) address.
Contd.
 Consider the statement
int xyz = 50;

– This statement instructs the compiler to allocate a


location for the integer variable xyz, and put the value 50
in that location.
– Suppose that the address location chosen is 1380.

Xyz  Variable
50  Value
1380  address
Contd.
 During execution of the program, the system always
associates the name xyz with the address 1380.
– The value 50 can be accessed by using either the name
xyz or the address 1380.
 Since memory addresses are simply numbers, they can be
assigned to some variables which can be stored in
memory.
– Such variables that hold memory addresses are called
pointers.
– Since a pointer is a variable, its value is also stored in
some memory location.
Contd.
 Suppose we assign the address of xyz to a variable p.
– p is said to point to the variable xyz.

Variable Value Address


p=&xyz;
xyz 50 1380
p 1380 2545
Address vs. Value
 Each memory cell has an address associated with it.

101 102 103 104 105 ……..

…… ……
Address vs. Value
 Each memory cell has an address associated with it.
 Each cell also stores some value.

101 102 103 104 105 ……..

50 76
…… ……
Address vs. Value
 Each memory cell has an address associated with it.
 Each cell also stores some value.
 Don‟t confuse the address referring to a memory location
with the value stored in that location.

101 102 103 104 105 ……..

……
50 76 ……
Values vs Locations

 Variables name memory locations, which hold values.

1024
32 Value

x
Address
Name
Pointers
 A pointer is just a C variable whose value is the address
of another variable!
 After declaring a pointer:
int *ptr;
ptr doesn‟t actually point to anything yet. We can either:
–make it point to something that already exists, or
– allocate room in memory for something new that it
will point to… (next time)
Pointer
int x;
int * xp ;
Pointer
int x;
Pointer to int
int * xp ;
Pointer
int x;
Pointer to int
int * xp ;

xp = &x ;
Pointer
int x;
Pointer to int
int * xp ;

xp = & x ;
Address of X
Pointer
int x;
Pointer to int
int * xp ;
1024: 32
xp = & x ;
Address of X
1024
Pointer
int x;
Pointer to int
int * xp ;
1024: 32
xp = & x ;
Address of X
1024

*xp = 0; /* Assign 0 to x */
*xp = *xp + 1; /* Add 1 to x */
Pointer
int x; Pointer to int
int * xp ;
1024: 32
xp = & x ;
Address of X
*xp = 0; /* Assign 0 to x */ 1024
*xp = *xp + 1; /* Add 1 to x */
Pointers
…..
Abstractly
(x == *p) True
int x;
(p == &x) True
int * p;
p=&x;
Pointers
 Declaring a pointer just allocates space to hold the
pointer – it does not allocate something to be pointed
to!
 Local variables in C are not initialized, they may
contain anything.
Pointer Usage Example
Pointer Usage Example
Pointer Usage Example
Pointer Usage Example
Pointer Usage Example
Recall
 Pointer Introduction
Accessing the Address of a Variable
 The address of a variable can be determined using the
„&‟ operator.
– The operator „&‟ immediately preceding a variable
returns the address of the variable.
 Example:
p = &xyz;
– The address of xyz (1380) is assigned to p.
 The „&‟ operator can be used only with a simple variable
or an array element.
&distance
&x[0]
&x[i-2]
Contd.
 Following usages are illegal:

&235
• Pointing at constant.

&(a+b)
• Pointing at expression.
Example
#include <stdio.h> Address of A: 3221224908
main() Address of B: 3221224904
{ Address of C: 3221224900
int a; Address of D: 3221224892
float b, c; Address of ch: 3221224891
double d;
char ch;
a = 10; b = 2.5; c = 12.36; d = 12345.66; ch = „A‟;
printf (“%d is stored in location %u \n”, a, &a) ;
printf (“%f is stored in location %u \n”, b, &b) ;
printf (“%f is stored in location %u \n”, c, &c) ;
printf (“%ld is stored in location %u \n”, d, &d) ;
printf (“%c is stored in location %u \n”, ch, &ch) ;
}
Output:
10 is stored in location 3221224908
2.500000 is stored in location 3221224904
12.360000 is stored in location 3221224900
12345.660000 is stored in location 3221224892
A is stored in location 3221224891
Pointer Declarations
 Pointer variables must be declared before we use them.
• General form:
data_type *pointer_name;

 Three things are specified in the above declaration:


• The asterisk (*) tells that the variable pointer_name
is a pointer variable.
• pointer_name needs a memory location.
• pointer_name points to a variable of type data_type.

pointer_name Variable
(data_type) (data_type)
Contd.
 Example:
int *count;
float *speed;

 Once a pointer variable has been declared, it can be made


to point to a variable using an assignment statement like:

int *p, xyz;


:
p = &xyz;
– This is called pointer initialization.
Things to Remember
 Pointer variables must always point to a data item of the
same type.

float x;
int *p;
: will result in erroneous output
p = &x;

 Assigning an absolute address to a pointer variable is


prohibited.

int *count;
:
count = 1268;
Accessing a Variable Through its Pointer
 Once a pointer has been assigned the address of a
variable, the value of the variable can be accessed
using the indirection operator (*).

int a, b;
int *p; b = a;
:
p = &a;
b = *p;
Example
#include <stdio.h>
main()
{
Equivalent
int a, b;
int c = 5;
int *p;
a = 4 * (c + 5) ;
p = &c;
b = 4 * (*p + 5) ;
printf (“a=%d b=%d \n”, a, b);
}
Example
#include <stdio.h>
main()
{
int x, y;
int *ptr;
x = 10 ;
ptr = &x ;
y = *ptr ;
printf (“%d is stored in location %u \n”, x, &x) ;
printf (“%d is stored in location %u \n”, *&x, &x) ;
printf (“%d is stored in location %u \n”, *ptr, ptr) ;
printf (“%d is stored in location %u \n”, y, &*ptr) ;
printf (“%u is stored in location %u \n”, ptr, &ptr) ;
printf (“%d is stored in location %u \n”, y, &y) ;
*ptr = 25;
printf (“\nNow x = %d \n”, x);
}
 Output:
10 is stored in location 3221224908
10 is stored in location 3221224908
10 is stored in location 3221224908
10 is stored in location 3221224908
3221224908 is stored in location 3221224900
10 is stored in location 3221224904
Now x = 25
Pointer Expressions
 Like other variables, pointer variables can be used in
expressions.

 If p1 and p2 are two pointers, the following statements


are valid:
sum = *p1 + *p2;
prod = *p1 * *p2;
prod = (*p1) * (*p2);
*p1 = *p1 + 2;
x = *p1 / *p2 + 5;
Contd.
 What are allowed in C?
– Add an integer to a pointer.
p1 = p2 + 2;
– Subtract an integer from a pointer.
p1 = p2 - 2;
– Subtract one pointer from another (related).
• If p1 and p2 are both pointers to the same array,
then p2– p1 gives the number of elements between
p1 and p2.
 What are not allowed?
– Add two pointers.
p1 = p1 + p2;
– Multiply / divide a pointer in an expression.
p1 = p2 / 5;
p1 = p1 – p2 * 10;
Scale Factor
 We have seen that an integer value can be added to or
subtracted from a pointer variable.
int *p1, *p2;
int i, j;
:
p1 = p1 + 1;
p2 = p1 + j;
p2++;
p2 = p2 – (i + j);

– In reality, it is not the integer value which is


added/subtracted, but rather the scale factor times the
value.
Contd.
Data Type Scale Factor
char 1
int 4
float 4
double 8

– If p1 is an integer pointer, then


p1++
will increment the value of p1 by 4.
Contd.
 Note:
– The exact scale factor may vary from one machine to
another.
– Can be found out using the sizeof function.
– Syntax:
sizeof (data_type)
Example: to find the scale factors
#include <stdio.h>
main()
{
printf (“No. of bytes occupied by int is %d \n”, sizeof(int));
printf (“No. of bytes occupied by float is %d \n”, sizeof(float));
printf (“No. of bytes occupied by double is %d \n”, sizeof(double));
printf (“No. of bytes occupied by char is %d \n”, sizeof(char));
}

Output:
Number of bytes occupied by int is 4
Number of bytes occupied by float is 4
Number of bytes occupied by double is 8
Number of bytes occupied by char is 1
void main()
{ Address of i: 1220
int i = 3 ; Address of j: 1450
int *j ;
j = &i ;
printf ( "\nAddress of i = %u", &i ) ;
printf ( "\nAddress of i = %u", j ) ;
printf ( "\nAddress of j = %u", &j ) ;
printf ( "\nValue of j = %u", j ) ;
printf ( "\nValue of i = %d", i ) ;
printf ( "\nValue of i = %d", *( &i ) ) ;
printf ( "\nValue of i = %d", *j ) ;
}
Passing Pointers to a Function
 Pointers are often passed to a function as arguments.
– Allows data items within the calling program to be
accessed by the function, altered, and then returned to
the calling program in altered form.
– Called call-by-reference (or by address or by location).
 Normally, arguments are passed to a function by value.
– The data items are copied to the function.
– Changes are not reflected in the calling program.
Example: passing arguments by value
#include <stdio.h>
main()
{
int a, b;
a = 5; b = 20; Output
swap (a, b); a=5, b=20
printf (“\n a=%d, b=%d”, a, b);
}
void swap (int x, int y)
{
int t;
t = x;
x = y;
y = t;
}
Example: passing arguments by reference
#include <stdio.h>
main()
{
int a, b;
a = 5; b = 20; Output
swap (&a, &b); a=20, b=5
printf (“\n a=%d, b=%d”, a, b);
}
void swap (int *x, int *y)
{
int t;
t = *x;
*x = *y;
*y = t;
}
Recall
 Pointer
 & operator and * operator
 int *p=&a;
 int *p;
 P=&a;
 *p=b;
 Pointer Expressions
 Call by Reference and Call by Value
Using a call by reference intelligently we can make a
function return more than one value at a time, which is not
possible ordinarily.
void areaperi ( int , float *, float * );
void main( )
{
int radius ;float area, perimeter ;
printf ( "\nEnter radius of a circle " ) ;
scanf ( "%d", &radius ) ;
areaperi ( radius, &area, &perimeter ) ;
printf ( "Area = %f", area ) ;
printf ( "\nPerimeter = %f", perimeter ) ;
}
void areaperi ( int r, float *a, float *p )
{
*a = 3.14 * r * r ;
*p = 2 * 3.14 * r ;
}
Pass by value and reference
(a) If we want that the value of an actual argument should not get
changed in the function being called, pass the actual argument
by value.
(b) If we want that the value of an actual argument should get
changed in the function being called, pass the actual argument
by reference.
(c) If a function is to be made to return more than one value at a
time then return these values indirectly by using a call by
reference.
Example
a) Write a function that receives 5 integers and returns the
sum, average and standard deviation of these numbers. Call
this function from main( ) and print the results in main( ).
b) Write a function that receives marks received by a student in
3 subjects and returns the average and percentage of these
marks. Call this function from main( ) and print the results
in main( ).
Pointers and Arrays
 When an array is declared,
– The compiler allocates a base address and sufficient
amount of storage to contain all the elements of the array
in contiguous memory locations.
– The base address is the location of the first element
(index 0) of the array.
– The compiler also defines the array name as a constant
pointer to the first element.
Example
 Consider the declaration:
int x[5] = {1, 2, 3, 4, 5};
– Suppose that the base address of x is 2500, and each
integer requires 4 bytes.

Element Value Address


x[0] 1 2500
x[1] 2 2504
x[2] 3 2508
x[3] 4 2512
x[4] 5 2516
Contd.
Both x and &x[0] have the value 2500.
p = x; and p = &x[0]; are equivalent.
– We can access successive values of x by using p++
or p– to move from one element to another.

 Relationship between p and x:


p = &x[0] = 2500
p+1 = &x[1] = 2504
p+2 = &x[2] = 2508
p+3 = &x[3] = 2512
p+4 = &x[4] = 2516
*(p+i) gives the
value of x[i]
Arrays and pointers
 An array name is an address, or a pointer value.
 Pointers as well as arrays can be subscripted.
 A pointer variable can take different addresses as values.
 An array name is an address, or pointer, that is fixed.
It is a CONSTANT pointer to the first element.
Arrays and pointers
 int a[20], i, *p;
• The expression a[i] is equivalent to *(a+i)
• p[i] is equivalent to *(p+i)
p[i]
*( p + i )
*( i + p )
i[p]
All are same.
• When an array is declared the compiler allocates a
sufficient amount of contiguous space in memory. The
base address of the array is the address of a[0].

• Suppose the system assigns 300 as the base address


of a. a[0], a[1], ...,a[19] are allocated 300, 304, ..., 376.
Arrays and pointers
#define N 20
int a[N], i, *p, sum;
• p = a; is equivalent to p = &a[0];
• p is assigned 300.
• Pointer arithmetic provides an alternative to array
indexing.
• p=a+1; is equivalent to p=&a[1]; (p is assigned 304)

for (p=a; p<&a[N]; ++p) p=a;


sum += *p ; for (i=0; i<N; ++i)
sum += p[i] ;
for (i=0; i<N; ++i)
sum += *(a+i) ;
Arrays
 Consequences:
–ar is a pointer
–ar[0] is the same as *ar
–ar[2] is the same as *(ar+2)
–We can use pointer arithmetic to access arrays more
conveniently.
Arrays
 Array size n; want to access from 0 to n-1, so you should
use counter AND utilize a constant for declaration & incre
Wrong
int i, ar[10];
for(i = 0; i < 10; i++){ ... }
Right
#define ARRAY_SIZE 10
int i, a[ARRAY_SIZE];
for(i = 0; i < ARRAY_SIZE; i++){ ... }
 •Why? SINGLE SOURCE OF TRUTH
 You‟re utilizing indirection and avoiding maintaining two
copies of the number 10
Arrays
 Pitfall: An array in C does not know its own length, &
bounds not checked!
– Consequence: We can accidentally access off the
end of an array.
– Consequence: We must pass the array and its size to
a procedure which is going to traverse it.
 Segmentation faults and bus errors:
– These are VERY difficult to find; be careful!
– You‟ll learn how to debug these in lab…
Recall
 Pointer
 Pointer expression
 Call by Reference and Call by Value
 Void pointer void *p;
 Arrays and pointers
Arrays and pointers
#define N 20
int a[N], i, *p, sum;
• p = a; is equivalent to p = &a[0];
• p is assigned 300.
• Pointer arithmetic provides an alternative to array
indexing.
• p=a+1; is equivalent to p=&a[1]; (p is assigned 304)

for (p=a; p<&a[N]; ++p) p=a;


sum += *p ; for (i=0; i<N; ++i)
sum += p[i] ;
for (i=0; i<N; ++i)
sum += *(a+i) ;
Example:
void main( )
{
int num[ ] = { 24, 34, 12, 44, 56, 17 } ;
int i, *j ;
j = &num[0] ; /* assign address of zeroth element */
for ( i = 0 ; i <= 5 ; i++ )
{
printf ( "\naddress = %u ", j ) ;
printf ( "element = %d", *j ) ;
j++ ; /* increment pointer to point to next location */
}
}
The output of this program would be:
address = 65512 element = 24
address = 65514 element = 34
address = 65516 element = 12
address = 65518 element = 44
address = 65520 element = 56
address = 65522 element = 17
void main( )
{
int arr[ ] = { 10, 20, 30, 45, 67, 56, 74 } ;
int *i, *j ;
i = &arr[1] ;
j = &arr[5] ;
printf ( "%d %d", j - i, *j - *i ) ;
}
void main( )
{
int arr[ ] = { 10, 20, 36, 72, 45, 36 } ;
int *j, *k ;
j = &arr [ 4 ] ;
k = ( arr + 4 ) ;
if ( j == k )
printf ( "The two pointers point to the same location" ) ;
else
printf ( "The two pointers do not point to the same location" ) ;
}
main( )
{
int num[ ] = { 24, 34, 12, 44, 56, 17 } ;
int i ;
for ( i = 0 ; i <= 5 ; i++ )
{
printf ( "\nelement no. %d ", i ) ;
printf ( "address = %u", &num[i] ) ;
}
}
main( )
{
int num[ ] = { 24, 34, 12, 44, 56, 17 } ;
int i, *j ;
j = &num[0] ; /* assign address of zeroth element */
for ( i = 0 ; i <= 5 ; i++ )
{
printf ( "\naddress = %u ", j ) ;
printf ( "element = %d", *j ) ;
j++ ; /* increment pointer to point to next location */
}
}
main( )
{
int num[ ] = { 24, 34, 12, 44, 56, 17 } ;
int i ;
for ( i = 0 ; i <= 5 ; i++ )
{
printf ( "\naddress = %u ", &num[i] ) ;
printf ( "element = %d %d ", num[i], *( num + i ) ) ;
printf ( "%d %d", *( i + num ), i[num] ) ;
}
}
Passing an Entire Array to a Function
main( )
{
int num[ ] = { 24, 34, 12, 44, 56, 17 } ;
dislpay ( &num[0], 6 ) ;
}
void display ( int *j, int n )
{
int i ;
for ( i = 0 ; i <= n - 1 ; i++ )
{
printf ( "\nelement = %d", *j ) ;
j++ ; /* increment pointer to point to next element */
}
}
Pointers and Strings
main( )
{
char name[ ] = "Klinsman" ;
char *ptr ;
ptr = name ; /* store base address of string */
while ( *ptr != `\0' )
{
printf ( "%c", *ptr ) ;
ptr++ ;
}
}
 Suppose we wish to store “Hello”. We may either store it in
a string or we may ask the C compiler to store it at some
location in memory and assign the address of the string in
a char pointer. This is shown below:
 char str[ ] = "Hello" ;
 char *p = "Hello" ;

main( )
{
char str1[ ] = "Hello" ;
char str2[10] ;
char *s = "Good Morning" ;
char *q ;
str2 = str1 ; /* error */
q = s ; /* works */
}
Arrays In Functions
 An array parameter can be declared as an array or a
pointer; an array argument can be passed as a pointer.
– Can be incremented

int strlen (char s[ ]) int strlen (char *s)


{ {

} }
We can use const in several situations. The following code
fragment would help you to fix your ideas about const further.

char *p = "Hello" ; /* pointer is variable so is string */


*p = 'M' ; /* works */
p = "Bye" ; /* works */
const char *q = "Hello" ; /* string is fixed, pointer is not */
*q = 'M' ; /* error */
q = "Bye" ; /* works */
char const *s = "Hello" ; /* string is fixed, pointer is not */
*s = 'M' ; /* error */
s = "Bye" ; /* works */
char * const t = "Hello" ; /* pointer is fixed, string is not */
*t = 'M' ; /* works */
t = "Bye" ; /* error */
const char * const u = "Hello" ; /* string is fixed so is pointer */
*u = 'M' ; /* error */
u = "Bye" ; /* error
Recall
 Pointer and array
 Pointer and string
Function returning Pointer
 A function can also return a pointer to the calling function. In
this case you must be careful, because local variables of
function doesn't live outside the function, hence if you return a
pointer connected to a local variable, that pointer be will
pointing to nothing when function ends.

 Safe ways to return a valid Pointer.


 Either use argument with functions. Because argument
passed to the functions are declared inside the calling function,
hence they will live outside the function called.
 Or, use static local variables inside the function and return it.
As static variables have a lifetime until main() exits, they will be
available througout the program.
#include <stdio.h>
int* larger(int*, int*);
void main()
{
int a=15;
int b=92;
int *p;
p=larger(&a, &b);
printf("%d is larger",*p);
}
int* larger(int *x, int *y)
{
if(*x > *y)
return x;
else
return y;
}
Pointers and 2-Dimensional Arrays
main( )
{ int s[4][2] = {
{ 1234, 56 },
{ 1212, 33 },
{ 1434, 80 },
{ 1312, 78 }
};
int i ;
for ( i = 0 ; i <= 3 ; i++ )
printf ( "\nAddress of %d th 1-D array = %u", i, s[i] ) ;
}
And here is the output...
Address of 0 th 1-D array = 65508
Address of 1 th 1-D array = 65512
Address of 2 th 1-D array = 65516
Address of 3 th 1-D array = 65520
s 0 1

0 1234 56

1 1212 33

2 1434 80

3 1312 78

We know that the expressions s[0] and s[1] would yield the addresses
of the zeroth and first one-dimensional array respectively. From
Figure these addresses turn out to be 65508 and 65512.
 Now, we have been able to reach each one-dimensional array.
What remains is to be able to refer to individual elements of a
one dimensional array.
 Suppose we want to refer to the element s[2][1] using pointers.
We know (from the above program) that s[2] would give the
address 65516, the address of the second one-dimensional
array. Obviously ( 65516 + 1 ) would give the address 65518.
Or ( s[2] + 1 ) would give the address 65518. And the value
at this address can be obtained by using the value at address
operator, saying *( s[2] + 1 ). But, we have already studied
while learning one-dimensional arrays that num[i] is same as
*( num + i ). Similarly, *( s[2] + 1 ) is same as, *( *( s + 2 ) + 1
).
 Thus, all the following expressions refer to the same element,
s[2][1]
* ( s[2] + 1 )
*(*(s+2)+1)
/* Pointer notation to access 2-D array elements */
main( )
{
int s[4][2] = {
{ 1234, 56 },
{ 1212, 33 },
{ 1434, 80 },
{ 1312, 78 }
};
int i, j ;
for ( i = 0 ; i <= 3 ; i++ )
{
printf ( "\n" ) ;
for ( j = 0 ; j <= 1 ; j++ )
printf ( "%d ", *( *( s + i ) + j ) ) ;
}}
 And here is the output...
1234 56
1212 33
1434 80
1312 78
char masterlist[6][10] = {
"akshay",
"parag",
"raman",
"srinivas",
"gopal",
"rajesh"
};
Dynamic Memory Allocation
Basic Idea

 Many a time we face situations where data is dynamic in


nature.
– Amount of data cannot be predicted beforehand.
– Number of data items keeps changing during
program execution.

 Such situations can be handled more easily and


effectively using dynamic memory management
techniques.
Cont.
 C language requires the number of elements in an array
to be specified at compile time.
– Often leads to wastage or memory space or
program failure.

 Dynamic Memory Allocation


– Memory space required can be specified at the
time of execution.
– C supports allocating and freeing memory
dynamically using library routines.
Memory Allocation Process in C
Contd.
 The program instructions and the global variables are
stored in a region known as permanent storage area.

 The local variables are stored in another area called


stack.

 The memory space between these two areas is


available for dynamic allocation during execution of
the program.
– This free region is called the heap.
– The size of the heap keeps changing.
Memory Allocation Functions
 malloc
– Allocates requested number of bytes and returns a
pointer to the first byte of the allocated space.
 calloc
– Allocates space for an array of elements, initializes
them to zero and then returns a pointer to the memory.
 free
– Frees previously allocated space.
 realloc
– Modifies the size of previously allocated space.
Allocating a Block of Memory
 A block of memory can be allocated using the function
malloc.
– Reserves a block of memory of specified size
and returns a pointer of type void.
– The return pointer can be type-casted to any
pointer type.

 General format:
ptr = (type *) malloc (byte_size);
Contd.
 Examples
p = (int *) malloc(100 * sizeof(int));
– A memory space equivalent to 100 times the size of
an int bytes is reserved.
– The address of the first byte of the allocated memory
is assigned to the pointer p of type int.

cptr = (char *) malloc (20);


– Allocates 20 bytes of space for the pointer cptr of
type char.
Points to Note
 malloc always allocates a block of contiguous bytes.
– The allocation can fail if sufficient contiguous
memory space is not available.
– If it fails, malloc returns NULL.

if ((p = (int *) malloc(100 * sizeof(int))) == NULL)


{
printf (“\n Memory cannot be allocated”);
exit();
}
Example
#include <stdio.h> printf("Input heights for %d students
main() \n",N);
{
for (i=0; i<N; i++)
int i,N;
scanf ("%f", &height[i]);
float *height;
float sum=0,avg; for(i=0;i<N;i++)
sum += height[i];
printf("Input no. of students\n");
scanf("%d", &N); avg = sum / (float) N;

height = (float *) printf("Average height = %f \n", avg);


malloc(N * sizeof(float));
free (height);
}
main()
{
int *ptr, *p, n;
printf(“\nEnter number of elements :”);
scanf(“%d”, &n);
ptr = (int*)malloc(n * sizeof(int));
if (ptr == NULL)
{
printf(“Not enough memory to allocate”);
Exit(1);
}
printf (“Enter values :”);
for(p = ptr; p< ptr + n; p++)
scanf(“%d”, p);
printf(“\nThe values input are :\n”);
for(p = ptr; p<ptr + n; p++)
printf(“Value = %d\tAddress = %u\n”, *p, p);
}
Releasing the Used Space
 When we no longer need the data stored in a block of
memory, we may release the block for future use.

 How?
– By using the free function.

 General syntax:
free (ptr);
where ptr is a pointer to a memory block which has
been previously created using malloc.
Altering the Size of a Block
 Sometimes we need to alter the size of some
previously allocated memory block.
– More memory needed.
– Memory allocated is larger than necessary.
 How?
– By using the realloc function.
 If the original allocation is done as:
ptr = malloc (size);
then reallocation of space may be done as:
ptr = realloc (ptr, newsize);
Realloc

 ptr= (type *)realloc(ptr, num_bytes);

 What it does (conceptually)


–Find space for new allocation
–Copy original data into new space
–Free old space
–Return pointer to new space
 The new memory block may or may not begin at the
same place as the old one.
• If it does not find space, it will create it in an
entirely different region and move the contents of
the old bloc k into the new block.
 The function guarantees that the old data remains
intact.
 If it is unable to allocate, it returns NULL and frees the
original block.
#include “stdlib.h”
main()
{
int *ptr, *p;
ptr = (int*)malloc(5 * sizeof(int));
if (ptr == NULL)
{
printf(“No space”);
exit(1);
}
printf(“Enter values :”);
for(p = ptr; p< ptr + 5; p++)
scanf(“%d”, p);
for(p = ptr; p < ptr+5; p++)
printf(“Value = %d\tAddress = %u\n”, *p, p);
ptr = (int*) realloc(ptr, 8 *sizeof(int));
if (ptr == NULL)
{
printf(“Reallocation Failed”);
exit(1);
}
printf(“New block reallocated succesfully”);
printf(“\nNew block contains :\n”);
for(p = ptr; p < ptr+5; p++)
printf(“Value = %d\tAddress = %u\n”, *p, p);
printf(“„Enter new values for the reallocated block”);
for(p = ptr; p < ptr + 8; p++)
scanf(“%d”, p);
printf(“New values in the list \n”);
for(p = ptr; p< ptr + 8; p++)
printf(“Value = %d\tAddress = %u\n”, *p, p);
calloc()
 calloc() is a variant of malloc()
 calloc() takes two arguments: the number of "things" to be
allocated and the size of each "thing" (in bytes)
 calloc() returns the address of the chunk of memory that was
allocated
 calloc() also sets all the values in the allocated memory to
zeros (malloc() doesn't)
 calloc() is also used to dynamically allocate arrays

 The general form of calloc() :


ptr = (cast-type*) calloc(n, element-size);
calloc()
 For instance, to dynamically allocate an array of 10 ints:
int*arr;
arr= (int*) calloc(10, sizeof(int));
/* now arr has the address
of an array of 10 ints, all 0s */
ptr = malloc(10 * sizeof(int)); is just like this:
ptr = calloc (10, sizeof(int));
 eg.
int arr1[10];
int *ptr;
ptr = (int*)calloc(10, sizeof(int));
-------
-------
 Here we have defined an array arr1 having ten elements of
type int. We use the calloc() function to reserve 10
blocks of size each equal to the size of int. The pointer is
returned to ptr of type int. It is important to check whether
space has been made available or not before further
execution.
malloc/calloc return value
 Malloc and calloc both return the address of the newly-
allocated block of memory
 However, they are not guaranteed to succeed!
–maybe there is no more memory available
 If they fail, they return NULL
 You must always check for NULL when using malloc or
calloc
Contd.
 bad:
int*arr= (int*) malloc(10 * sizeof(int));
/* code that uses arr... */

 good:

int*arr= (int*) malloc(10 * sizeof(int));


if (arr== NULL) {
printf("out of memory!\n");
exit(1);
}
 Always do this!
malloc()vs. calloc()

 malloc/calloc both allocate memory

 calloc() zeros out allocated memory, malloc()doesn't.


storage class
 A storage class defines the scope visibility and life-time of
variables and/or functions within a C Program. These
specifiers precede the type that they modify. There are the
following storage classes, which can be used in a C Program
 auto
 register
 static
 extern
The auto Storage Class
 The auto storage class is the default storage class for
all local variables.
{
int month;
auto int month;
}
 The example above defines two variables with the same
storage class, auto can only be used within functions, i.e.,
local variables.
The static Storage Class
 The static storage class instructs the compiler to keep
a local variable in existence during the lifetime of the
program instead of creating and destroying it each time it
comes into and goes out of scope.
 Therefore, making local variables static allows them to
maintain their values between function calls.
 The static modifier may also be applied to global variables.
When this is done, it causes that variable's scope to be
restricted to the file in which it is declared.
 In C programming, when static is used on a class data
member, it causes only one copy of that member to be
shared by all objects of its class.
void func(void); /* function declaration * /
static int count = 5; /* global variable * /
main()
{
while(count--)
{
func();
}
return 0;
}
/* function definition * /
void func( void )
{
static int i = 5; /* local static variable * /
i++;
printf("i is %d and count is %d\n", i, count);
i is 6 and count is 4
i is 7 and count is 3
i is 8 and count is 2
i is 9 and count is 1
i is 10 and count is 0
void pointer
 Not originally in c
 Relatively recent addition
 Basically a “generic” pointer

 Intended for use in applications like free where the block of


memory located at some address will be freed without any
necessity of defining the type
Thank You
 Thank You

You might also like