Memory Management for C and C++ _ language

23ecuos117 23 views 28 slides Aug 13, 2024
Slide 1
Slide 1 of 28
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28

About This Presentation

Related of c programming memory management


Slide Content

Pointers
one of the strongest but also one of the most dangerous features in C
an invalid value can cause your program to crash.
Easy to use incorrectly, causing bugs that are very difficult to find

Data Storage
stored data items occupy
one or more contiguous memory cells.
No. of cells depends on type (char, int, double)
variable declaration
memory allocated to hold the value
Since every byte in memory has a unique address,
this location will have own address.

Address
•Consider the statement
int xyz = 50;
Compiler allocates a location for int xyz,
put 50 in that location.
Suppose that the address location chosen is 1380.
xyz  variable
50  value
1380  address

Pointer
During execution of the program,
xyz associated with address 1380
value 50 can be accessed by
xyz or the address 1380
memory addresses are simply numbers
assigned to variables which can be stored in mem.
Such variables holding memory addresses –
pointers
pointer – a variable
value stored in some memory location.

Address Assignment
assign the address of xyz to a variable p.
p points to variable xyz.
Variable Value Address
xyz 50 1380
p 1380 2545
p = &xyz;
501380
xyz
13802545
p

Pointer Initialization
int *count;
float *speed;
Once a pointer variable has been declared
can point to a variable using assignment
int *p, xyz;
:
p = &xyz;
pointer initialization.

passing arguments by value
#include <stdio.h>
main()
{
int a, b;
a = 5 ; b = 20 ;
swap (a, b) ;
printf (“\n a = %d, b = %d”, a, b);
}
void swap (int x, int y)
{
int t ;
t = x ;
x = y ;
y = t ;
}

passing arguments by value
#include <stdio.h>
main()
{
int a, b;
a = 5 ; b = 20 ;
swap (a, b) ;
printf (“\n a = %d, b = %d”, a, b);
}
void swap (int x, int y)
{
int t ;
t = x ;
x = y ;
y = t ;
}
Output
a = 5, b = 20
x and y swap
a and b
do not
swap

passing arguments by reference
#include <stdio.h>
main()
{
int a, b;
a = 5 ; b = 20 ;
swap (&a, &b) ;
printf (“\n a = %d, b = %d”, a, b);
}
void swap (int *x, int *y)
{
int t ;
t = *x ;
*x = *y ;
*y = t ;
}

passing arguments by reference
#include <stdio.h>
main()
{
int a, b;
a = 5 ; b = 20 ;
swap (&a, &b) ;
printf (“\n a = %d, b = %d”, a, b);
}
void swap (int *x, int *y)
{
int t ;
t = *x ;
*x = *y ;
*y = t ;
}
Output
a = 20, b = 5
*x and *y
swap
*(&a) and *(&b)
swap

Arrays and Addressess
Array declaration
compiler allocates base address with
amount of storage to contain all the
elements
in contiguous memory locations.
base address – location of first element (index 0)
array name – constant pointer to the first element
int x[5] = {1, 2, 3, 4, 5} ;
Element Value Address
x[0] 1 2500
x[1] 2 2504
x[2] 3 2508
x[3] 4 2512
x[4] 5 2516

Pointers and Arrays
x  &x[0]  2500 ;
p = x; and p = &x[0]; equivalent.
p++ or p- - access successive values of x
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]
all pointer operations are done relative to pointer's base type

Dynamic Memory Allocation

Dynamic nature of data
Amount of data cannot be predicted beforehand.
No. of data item keeps changing during execution
dynamic memory management techniques
handle Such situations more easily and
effectively.
–Memory required specified at time of execution.
–C supports allocating and freeing memory
dynamically using library routines

C Storage Areas
Local variables
Free memory
Global variables
Instructions
Permanent storage area
Stack
Heap
The memory space between permanent storage and Stack
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

Static vs Dynamic allocation
efficiency in terms of memory/execution time
Allocation – compile time / run time
Dynamic memory allocation
memory allocation is controlled by programmer
life time of an object is directly under control
unrelated to the block structure of the program.
A data object created inside a block remains in existence
until it is explicitly destroyed.

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.

Malloc( )
•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 assigned to any pointer type.
•char *p;
•p = malloc(1000); /* get 1000 bytes */
•After the assignment, p points to the first of 1,000
bytes of free memory
•General format:
ptr = (type *) malloc (byte_size) ;

void pointer
•generic pointer
•specifies a pointer whose base type is unknown.
•allows a function to specify a parameter
that can receive any type of pointer argument
without reporting a type mismatch.
•used to refer to raw memory such as that returned by
malloc( )
•No explicit cast required to convert to or from a void * pointer.

Allocation of Integers
p = (int *) malloc (100 * sizeof (int)) ;
Space 100 times the size of int bytes reserved
address of the first byte assigned to p
pointer of type int
p
400 bytes of space
sptr = (struct stud *) malloc (10 * sizeof (struct stud));

Allocation Failure
•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.

Releasing the Used Space
•No need of data stored in memory
release the block for other
use
•General format:
free (ptr) ;
ptr – pointer to mem. block created by malloc

Altering the Size of a Block
previously allocated memory block.
–More memory needed.
–Memory allocated is larger than necessary.
realloc( )
original allocation – ptr = malloc (size) ;
reallocation – ptr = realloc (ptr, newsize) ;

Reallocation
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 block
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.

Free Store Operators - new and delete
No inbuilt feature for garbage collection like other OOP languages
new – allocate memory
delete - deallocate memory allocated using new
Mixed use of dynamic memory allocation features of c and c++ not permitted.
pointer-variable = new data-type(value); // data-type - fundamental or user-defined
pointer-variable - pointer to data-type
e.g. int *p1; p1 = new int;
e.g. int *p2 = new int; *p2 = 10;
e.g. float *p3 = new float(25.5);
delete pointer-variable;
pointer-variable must be pointer returned by new (which is not already deleted)
e.g. delete p1;
Frees memory, does not delete pointer itself
Unary operators

Memory for array
can be allocated using new
pointer-variable = new data-type(value);
pointer-variable – holds address of the memory space allocated
int *p1 = new int(10); // initializer
Create memory space for any data type including arrays, structures and classes
e.g. int *p4 = new int[10]; // 10 integers
e.g. int *p5 = new int[10](); //Initialize all elements with 0
e.g. int *p6 = new int[10]{1, 2, 3}; //c++11
int bar [5] = { 10, 20, 30 };
int (*p7)[5] = new int[4][5];//multi-dimentional arrays - all sizes must be supplied
int (*p8)[5] = new int[m][5];// First dimention can be variable, others must be constant.
delete [size] pointer-variable;// programmer should remember the size of the array.
Recent versions of c++ - e.g. delete [ ] p4; //size not essential

If call to new fails - bad_alloc exception
If call to delete fails then also program will terminate like free
good practice - free the memory when no longer required
If you do not free the memory explicitly - freed when program execution ends
Advantages of new over malloc
Automatically computes size
Returns correct pointer type (No explicit type cast needed)
Possible to initialize value while allocating memory
new and delete operators could be overloaded

28
Reference Variables Example
#include <iostream.h>
// Function prototypes
(required in C++)
void p_swap(int *, int *);
void r_swap(int&, int&);
int main (void){
int v = 5, x = 10;
cout << v << x << endl;
p_swap(&v,&x);
cout << v << x << endl;
r_swap(v,x);
cout << v << x << endl;
return 0;
}
void r_swap(int &a, int &b)
{
int temp;
temp = a; (2)
a = b; (3)
b = temp;
}
void p_swap(int *a, int *b)
{
int temp;
temp = *a; (2)
*a = *b; (3)
*b = temp;
}