+ All Categories
Home > Documents > Prachi A. Joshi Assistant Professor in CSE DIEMS,Aurangabad Unit 1 : Basic Concepts Pointers and...

Prachi A. Joshi Assistant Professor in CSE DIEMS,Aurangabad Unit 1 : Basic Concepts Pointers and...

Date post: 17-Jan-2016
Category:
Upload: carmel-joseph
View: 219 times
Download: 0 times
Share this document with a friend
Popular Tags:
30
Pointers in C Prachi A. Joshi Assistant Professor in CSE DIEMS,Aurangabad Unit 1 : Basic Concepts Pointers and dynamic memory allocation, Algorithm Specification, Data abstraction, Performance analysis, Performance measurement
Transcript
Page 1: Prachi A. Joshi Assistant Professor in CSE DIEMS,Aurangabad Unit 1 : Basic Concepts Pointers and dynamic memory allocation, Algorithm Specification, Data.

Pointers in C

Prachi A. JoshiAssistant Professor in CSE

DIEMS,Aurangabad

Unit 1 : Basic Concepts

Pointers and dynamic memory allocation, Algorithm Specification, Data

abstraction, Performance analysis, Performance measurement

Page 2: Prachi A. Joshi Assistant Professor in CSE DIEMS,Aurangabad Unit 1 : Basic Concepts Pointers and dynamic memory allocation, Algorithm Specification, Data.

Concept of basic programming in C should be clear.

Array concepts must be clear.

Knowledge of representation of these data types at the

machine level, including their similarities and differences.

Pointers in C 2

Prerequistes

Page 3: Prachi A. Joshi Assistant Professor in CSE DIEMS,Aurangabad Unit 1 : Basic Concepts Pointers and dynamic memory allocation, Algorithm Specification, Data.

Pointers in C 3

Arrays in C

No bounds checking!Allowed – usually causes no errorarray[10] may overwrite b

int array[10];int b;

array[0] = 3;array[9] = 4;array[10] = 5;array[-1] = 6;

Compare: C: int array[10];

All elements of same type – homogenous

First element (index 0)Last element (index size - 1)

Page 4: Prachi A. Joshi Assistant Professor in CSE DIEMS,Aurangabad Unit 1 : Basic Concepts Pointers and dynamic memory allocation, Algorithm Specification, Data.

Homogeneous Each element same size – s bytes

◦ An array of m data values is a sequence of ms bytes

◦ Indexing: 0th value at byte s0, 1st value at byte s1, …

m and s are not part of representation

Pointers in C 4

Array Representation

a[0]

a[1]

a[2]

0x1000

0x1004

0x1008

int a[3];

Page 5: Prachi A. Joshi Assistant Professor in CSE DIEMS,Aurangabad Unit 1 : Basic Concepts Pointers and dynamic memory allocation, Algorithm Specification, Data.

What is

sizeof(array[3])?

sizeof(array)?

Pointers in C 5

Array Sizes

int array[10];

4

40

returns the size of an object in bytes

Page 6: Prachi A. Joshi Assistant Professor in CSE DIEMS,Aurangabad Unit 1 : Basic Concepts Pointers and dynamic memory allocation, Algorithm Specification, Data.

Pointers in C 6

Multi-Dimensional Arrays

int matrix[2][3];

matrix[1][0] = 17;

matrix[0][0]

matrix[0][1]

matrix[0][2]

0x1000

0x1004

0x1008

matrix[1][0]

matrix[1][1]

matrix[1][2]

0x100C

0x1010

0x1014

“Row Major”Organization

Page 7: Prachi A. Joshi Assistant Professor in CSE DIEMS,Aurangabad Unit 1 : Basic Concepts Pointers and dynamic memory allocation, Algorithm Specification, Data.

Pointers are fundamental to C .

C provides extensive support for pointer .

Example :

int i , *pi;

pi=&i;

Pointers in C 7

Pointers

& : Address Operator * : Dereferencing or Indirection operator

Page 8: Prachi A. Joshi Assistant Professor in CSE DIEMS,Aurangabad Unit 1 : Basic Concepts Pointers and dynamic memory allocation, Algorithm Specification, Data.

Creation& variable Returns variable’s memory address

Dereference• pointer Returns contents stored at address

Indirect assignment* pointer = val Stores value at address

Assignmentpointer = ptr Stores pointer in another variable

Pointers in C 8

Pointer Operations in C

Page 9: Prachi A. Joshi Assistant Professor in CSE DIEMS,Aurangabad Unit 1 : Basic Concepts Pointers and dynamic memory allocation, Algorithm Specification, Data.

pointer + number pointer – number

E.g., pointer + 1 adds 1 something to a pointer

Pointers in C 9

Pointer Arithmetic

char *p;char a;char b;

p = &a;p += 1;

int *p;int a;int b;

p = &a;p += 1;In each, p now points to b

(Assuming compiler doesn’t reorder variables in memory)

Adds 1*sizeof(char) to the memory address

Adds 1*sizeof(int) to the memory address

Pointer arithmetic should be used carefully

Page 10: Prachi A. Joshi Assistant Professor in CSE DIEMS,Aurangabad Unit 1 : Basic Concepts Pointers and dynamic memory allocation, Algorithm Specification, Data.

Special constant pointer NULL◦ Points to no data◦ Dereferencing illegal – causes segmentation fault

◦ To define, include <stdlib.h> or <stdio.h>

Pointers in C 10

The Simplest Pointer in C

Page 11: Prachi A. Joshi Assistant Professor in CSE DIEMS,Aurangabad Unit 1 : Basic Concepts Pointers and dynamic memory allocation, Algorithm Specification, Data.

Pointers in C 11

Pass-by-Referencevoid swap(int *x,int *y){ *x = 1001; *y = 1002;}

void f(void){ int a = 1; int b = 2; swap(&a,&b);}

1

2

a

b

x

y

1001

1002

Page 12: Prachi A. Joshi Assistant Professor in CSE DIEMS,Aurangabad Unit 1 : Basic Concepts Pointers and dynamic memory allocation, Algorithm Specification, Data.

Pointers in C 12

Arrays and Pointers

int i;int array[10];

for (i = 0; i < 10; i++){ array[i] = …;}

int *p;int array[10];

for (p = array; p < &array[10]; p++){ *p = …;}

These two blocks of code are functionally equivalent

Page 13: Prachi A. Joshi Assistant Professor in CSE DIEMS,Aurangabad Unit 1 : Basic Concepts Pointers and dynamic memory allocation, Algorithm Specification, Data.

In C, strings are just an array of characters◦ Terminated with ‘\0’ character◦ Arrays for bounded-length strings◦ Pointer for constant strings (or unknown length)

Pointers in C 13

Strings

char str1[15] = “Hello, world!\n”;char *str2 = “Hello, world!\n”;

H e l l o , w lo r d !\nlength

H e l l o , w lo r d !\nterminator

Pascal, Java, …

C, …

C terminator: ’\0’

Page 14: Prachi A. Joshi Assistant Professor in CSE DIEMS,Aurangabad Unit 1 : Basic Concepts Pointers and dynamic memory allocation, Algorithm Specification, Data.

Memory allocation is a process by which computer programs and

services are assigned with physical or virtual memory space.

Memory allocation is primarily a computer hardware operation but is

managed through operating system and software applications

Memory allocation has two core types,

1. Static Memory Allocation: The program is allocated memory at

compile time.

2.Dynamic Memory Allocation: The programs are allocated with

memory at run time.

Memory Allocation

Pointers in C 14

Page 15: Prachi A. Joshi Assistant Professor in CSE DIEMS,Aurangabad Unit 1 : Basic Concepts Pointers and dynamic memory allocation, Algorithm Specification, Data.

Types of Memory Allocation

Pointers in C 15

Static Memory Allocation Dynamic Memory Allocation

Memory is allocated before the execution of the program begins.(During Compilation)

Memory is allocated during the execution of the program.

No memory allocation or deallocation actions are performed during Execution.

Memory Bindings are established and destroyed during the Execution.

Variables remain permanently allocated.

Allocated only when program unit is active.

Implemented using stacks and heaps Implemented using data segments.

Pointer is needed to accessing variables.

No need of Dynamically allocated pointers.

Faster execution than Dynamic Slower execution than static

More memory Space required. Less Memory space required.

Page 16: Prachi A. Joshi Assistant Professor in CSE DIEMS,Aurangabad Unit 1 : Basic Concepts Pointers and dynamic memory allocation, Algorithm Specification, Data.

16

Overview of memory management

Pointers in C

Stack-allocated memory

1. When a function is called, memory is allocated for all of its parameters and local

variables.

2. Each active function call has memory on the stack (with the current function call on

top)

3. When a function call terminates, the memory is deallocated (“freed up”)

Ex: main() calls f(),

f() calls g()

g() recursively calls g()

main()

f()

g()

g()

Page 17: Prachi A. Joshi Assistant Professor in CSE DIEMS,Aurangabad Unit 1 : Basic Concepts Pointers and dynamic memory allocation, Algorithm Specification, Data.

17

Overview of memory management

Pointers in C

Heap-allocated memory

1. This is used for persistent data, that must survive beyond the lifetime of

a function call

global variables

dynamically allocated memory – C statements can create new heap

data .

2. Heap memory is allocated in a more complex way than stack memory

3. Like stack-allocated memory, the underlying system determines where to

get more memory – the programmer doesn’t have to search for free

memory space.

Page 18: Prachi A. Joshi Assistant Professor in CSE DIEMS,Aurangabad Unit 1 : Basic Concepts Pointers and dynamic memory allocation, Algorithm Specification, Data.

Dynamic memory functions

In the stdlib.h library:

malloc( )

Allocates specified number of bytes

calloc( )

Allocates specified number of bytes and initializes to zero.

realloc( )

Increases or decreases size of specified block of memory.

free( )

De-allocate memory, returns specified block of memory back to the

system.

Page 19: Prachi A. Joshi Assistant Professor in CSE DIEMS,Aurangabad Unit 1 : Basic Concepts Pointers and dynamic memory allocation, Algorithm Specification, Data.

malloc ( )Syntax : void * malloc (size_t size); Specifies in bytes the size of the area you want to reserve the argument. 

It returns the address as the return value of the dynamically allocated area. In

addition, returns NULL if it fails to secure the area.

Example : int *p = (int *) malloc (sizeof (int));

Page 20: Prachi A. Joshi Assistant Professor in CSE DIEMS,Aurangabad Unit 1 : Basic Concepts Pointers and dynamic memory allocation, Algorithm Specification, Data.

calloc ( )

Syntax : void *calloc(size_t nitems, size_t size)

where , nitems -- This is the number of elements to be allocated. size -- This is the size of elements.

This function returns a pointer to the allocated memory, or NULL if the request fails.

The difference in malloc and calloc is that malloc does not set the memory to zero where as calloc sets allocated memory to zero.

Example : a = (int *)calloc(n, sizeof(int));

Page 21: Prachi A. Joshi Assistant Professor in CSE DIEMS,Aurangabad Unit 1 : Basic Concepts Pointers and dynamic memory allocation, Algorithm Specification, Data.

realloc ( )

Syntax : void *realloc(void *ptr, size_t size)

where ,

ptr -- This is the pointer to a memory block previously allocated with malloc, calloc or realloc to be

reallocated. If this is NULL, a new block is allocated and a pointer to it is returned by the function.

size -- This is the new size for the memory block, in bytes. If it is 0 and ptr points to an existing

block of memory, the memory block pointed by ptr is deallocated and a NULL pointer is returned.

realloc( ) attempts to resize the memory block pointed to by ptr that was previously

allocated with a call to malloc or calloc.

Page 22: Prachi A. Joshi Assistant Professor in CSE DIEMS,Aurangabad Unit 1 : Basic Concepts Pointers and dynamic memory allocation, Algorithm Specification, Data.

void pointer in C is known as generic pointer.

Generic pointer is a pointer which can point type of data.

NULL pointer is a pointer which is pointing to nothing.

int *ptr=NULL;

NULL pointer points the base address of segment.

NULL is macro constant which has been defined in the

header files such as stdio.h,alloc.h,mem.h,stddef.h,stdlib.h

Pointers in C 22

Generic Pointer

Page 23: Prachi A. Joshi Assistant Professor in CSE DIEMS,Aurangabad Unit 1 : Basic Concepts Pointers and dynamic memory allocation, Algorithm Specification, Data.

A pointer in C which has not been initialized is known as

wild pointer.

Example :

void main( )

{

int *ptr;

printf(“\n %u”,ptr);

printf(“\n%d”,*ptr);

} Pointers in C 23

Wild Pointer

Output : Any address

Garbage Value

Page 24: Prachi A. Joshi Assistant Professor in CSE DIEMS,Aurangabad Unit 1 : Basic Concepts Pointers and dynamic memory allocation, Algorithm Specification, Data.

Dangling pointers and wild pointers in computer programming are pointers that do not point to a valid object of the appropriate type.

Dangling pointers arise during object destruction, when an object that has an incoming reference is deleted or deallocated, without modifying the value of the pointer, so that the pointer still points to the memory location of the deallocated memory.

As the system may reallocate the previously freed memory to another process, if the original program then dereferences the (now) dangling pointer, unpredictable behavior may result, as the memory may now contain completely different data. This is especially the case if the program writes data to memory pointed by a dangling pointer, a silent corruption of unrelated data may result, leading to subtle bugs that can be extremely difficult to find, or cause segmentation faults (UNIX, Linux) or general protection faults (Windows).

Dangling Pointers

Pointers in C 24

Page 25: Prachi A. Joshi Assistant Professor in CSE DIEMS,Aurangabad Unit 1 : Basic Concepts Pointers and dynamic memory allocation, Algorithm Specification, Data.

Dangling pointers and wild pointers in computer programming are pointers that do not point to a valid object of the appropriate type.

Dangling pointers arise during object destruction, when an object that has an incoming reference is deleted or deallocated, without modifying the value of the pointer, so that the pointer still points to the memory location of the deallocated memory.

As the system may reallocate the previously freed memory to another process, if the original program then dereferences the (now) dangling pointer, unpredictable behavior may result, as the memory may now contain completely different data. This is especially the case if the program writes data to memory pointed by a dangling pointer, a silent corruption of unrelated data may result, leading to subtle bugs that can be extremely difficult to find, or cause segmentation faults (UNIX, Linux) or general protection faults (Windows).

Dangling Pointers

Pointers in C 25

Page 26: Prachi A. Joshi Assistant Professor in CSE DIEMS,Aurangabad Unit 1 : Basic Concepts Pointers and dynamic memory allocation, Algorithm Specification, Data.

1. Character Pointer is Declared in the first Step.

2. After some statements we have deallocated memory which is previously

allocated.

3. As soon as “Memory is Deallocated Pointer is now Dangling“.

Dangling Pointers

Pointers in C 26

#include<stdlib.h> { char *ptr = malloc(Constant_Value); ....... ....... ....... free (ptr); /* ptr now becomes a dangling pointer */ }

Page 27: Prachi A. Joshi Assistant Professor in CSE DIEMS,Aurangabad Unit 1 : Basic Concepts Pointers and dynamic memory allocation, Algorithm Specification, Data.

After deallocating memory  Initialize Pointer to NULL so that pointer is now no longer dangling .

Initializing Pointer Variable to NULL Value means “Now Pointer is not pointing to anywhere“.

Dangling Pointers

Pointers in C 27

#include<stdlib.h> { char *ptr = malloc(Constant_Value); ....... ....... ....... free (ptr); /* ptr now becomes a dangling pointer */ ptr = NULL /* ptr is no more dangling pointer */ }

Page 28: Prachi A. Joshi Assistant Professor in CSE DIEMS,Aurangabad Unit 1 : Basic Concepts Pointers and dynamic memory allocation, Algorithm Specification, Data.

1. Character Pointer is Declared in the first Step.

2. Pointer Variable ‘ptr’ is pointing to Character Variable ‘ch’ declared in the inner block .

3. As character variable is non-visible in Outer Block , then Pointer is Still Pointing to Same Invalid memory location in Outer block , then Pointer becomes “Dangling”

Dangling Pointers

Pointers in C 28

#include<stdlib.h> void main( ) { char *ptr = NULL; ..... ..... { char ch; ptr = &ch; } ..... /* ptr is now a dangling pointer */ }

Page 29: Prachi A. Joshi Assistant Professor in CSE DIEMS,Aurangabad Unit 1 : Basic Concepts Pointers and dynamic memory allocation, Algorithm Specification, Data.

Uninitialized pointers might cause (1)segmentation fault.

Dynamically allocated block needs to be freed explicitly.  Otherwise, it

would lead to (2) memory leak.

Pointers are slower than normal variables.

If pointers are updated with incorrect values, it might lead to memory

corruption. (1) A segmentation fault occurs when a program attempts to access a memory

 location that it is not allowed to access. (2) In computer science, a memory leak occurs when a computer program

 incorrectly manages memory allocations

Pointers can be dangerous

Pointers in C 29

Page 30: Prachi A. Joshi Assistant Professor in CSE DIEMS,Aurangabad Unit 1 : Basic Concepts Pointers and dynamic memory allocation, Algorithm Specification, Data.

Pointers have the same size as type int. Since int is the default type specifier,

some programmers omit the return type when defining a function. Here the

return type defaults to int which can later be interpreted as a pointer.

Sometimes it is mandatory to use explicit type casts when converting

between pointer types .

pi = malloc(sizeof(int)); // Assign to pi a pointer to int

pf=(float *)pi;// Casts an int pointer to a float pointer

Pointers can be dangerous

Pointers in C 30


Recommended