Chapter 6 Data Types
description
Transcript of Chapter 6 Data Types
Chapter 6
Data Types
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
Pointer Type
A pointer has a memory address as it value (r-value), and also has a special value, nil (NULL in C)Pointer operations:
•Assignment: Sets a pointer variable’s value to some useful address(&) .
•Dereferncing: Fetches the value in the memory cell whose address is referenced
by the pointer(*) .
30
Pointer Types (C)
#include<stdio.h;>int main{()
int k, n; int *p;//Pointer declaration
k = 560; p = &k;//Pointer assignment
n = *p;//Pointer dereferencing printf("\n n = %d ",n); //Prints 560
return(0);}
31
Pointer Variables - Applications
Indirect addressing ( p=&k )
Array addressing ( *(mat+3) )
Record Field addressing ( s->id )
Allocation of dynamic storage
)p = (int*) malloc(64) ;(
32
Dangling Reference
•A dangling reference is a pointer that contains address of a dynamic variable that has been
deallocated .–Pointer “p1” is set to point to a new heap-dynamic
variable.–Pointer “p2” is assigned p1’s value.
–The heap dynamic variable pointed to by “p1” is explicitly deallocated , and p1 is set to null. Pointer p2 is not changed. p2 is now a dangling reference.
33
Dangling Reference
Heapp1
p2
Heapp1 (NULL)
p2
(Deallocated)
34
Dangling Reference
ProblemsThe location being pointed to by p2 may have been reallocated to some new heap-dynamic
variable .The new value will bear no relationship with the old
pointer’s dereferenced value . If p2 is used to change the heap dynamic variable,
then the value of the new heap dynamic variable will be destroyed.
35
Lost ObjectA lost heap-dynamic variable (lost object) is an allocated heap-dynamic variable that is no longer accessible to the user program, but still contains some useful data.
Pointer p1 is set to point to a heap-dynamic variable.
p1 is set to point to another heap dynamic variable. The first heap-dynamic variable is now inaccessible, or lost.
36
Lost Object
Heapp1
Heapp1
Heap
Lost object
37
Pointers and Java•Java does not provide indirect addressing
(&) and dereferencing operators .(*) •Java also does not allow any pointer
arithmetic .•Java does not allow explicit deallocation
of storage. There is no explicit deallocation operator (such as “delete”).
Since storage cannot be explicitly deallocated, you cannot have a dangling reference in Java.
38
Heap Management
•Never reassign a pointer variable which has a dynamic storage allocation. Before reassigning a pointer, make sure that the storage it points to, is deallocated.
•Immediately after deallocating a heap-dynamic storage, reset to null all the pointer variables pointing to it.
•Whenever a large storage allocation from heap is requested, check if enough memory is available.