26
Advanced Use of Pointers CS2023 Winter 2004

Advanced Use of Pointers - UNB · 2004-02-17 · Outcomes: Advanced use of Pointers fiC for Java Programmersfl, Chapter 8, section 8.11, 8.15 Other textbooks on C on reserve After

  • Upload
    others

  • View
    6

  • Download
    1

Embed Size (px)

Citation preview

Page 1: Advanced Use of Pointers - UNB · 2004-02-17 · Outcomes: Advanced use of Pointers fiC for Java Programmersfl, Chapter 8, section 8.11, 8.15 Other textbooks on C on reserve After

Advanced Use of Pointers

CS2023 Winter 2004

Page 2: Advanced Use of Pointers - UNB · 2004-02-17 · Outcomes: Advanced use of Pointers fiC for Java Programmersfl, Chapter 8, section 8.11, 8.15 Other textbooks on C on reserve After

Outcomes: Advanced use of Pointers

� “C for Java Programmers”, Chapter 8, section 8.11, 8.15

� Other textbooks on C on reserve

� After the conclusion of this section you should be able to

� Allocate and deallocate blocks of memory dynamically on the head

� Use pointers to functions in order to pass a function as a parameter to another function

� Use generic pointers to write more general functions

Page 3: Advanced Use of Pointers - UNB · 2004-02-17 · Outcomes: Advanced use of Pointers fiC for Java Programmersfl, Chapter 8, section 8.11, 8.15 Other textbooks on C on reserve After

Dynamic Memory Allocation

� C's data structures normally fixed in size

� C supports dynamic memory allocation to allocate storage during execution

� needed for dynamic arrays, lists, strings, ...

� Dynamically allocated memory stored on the heap

Page 4: Advanced Use of Pointers - UNB · 2004-02-17 · Outcomes: Advanced use of Pointers fiC for Java Programmersfl, Chapter 8, section 8.11, 8.15 Other textbooks on C on reserve After

Recall: Memory Management

� Dynamically allocated variables

� Memory allocated and destroyed at run time, under control of programmer!

� No guarantee that first variable to be destroyed is last created

� This area of memory can have holes and is called the heap

Page 5: Advanced Use of Pointers - UNB · 2004-02-17 · Outcomes: Advanced use of Pointers fiC for Java Programmersfl, Chapter 8, section 8.11, 8.15 Other textbooks on C on reserve After

Recall: Memory Management

� Usually heap and stack begin at opposite ends of the program's memory, and grow towards each other

�� � � � � � � � � � � � ���� � �� ��

� � � � ��� �

� � � � � � � � � � � � � � �

Page 6: Advanced Use of Pointers - UNB · 2004-02-17 · Outcomes: Advanced use of Pointers fiC for Java Programmersfl, Chapter 8, section 8.11, 8.15 Other textbooks on C on reserve After

Dynamic Memory Allocation

�� � � � ! Allocates a block of memory, but doesn't initialize it

! � � � � ! Allocates a block of memory and clears it

" Note: arguments of �� � � � ! and ! � � � � ! of type # $&% ')( *

, which is type returned by sizeof operator (normally + , # $ - , ' . � � ,- )

Page 7: Advanced Use of Pointers - UNB · 2004-02-17 · Outcomes: Advanced use of Pointers fiC for Java Programmersfl, Chapter 8, section 8.11, 8.15 Other textbooks on C on reserve After

Dynamic Memory AllocationTwo primary methods of allocating memory:

/ 0 12 354 6 7 7 08 9 : 1&; <)= > ? <@ A <: > < 2 B 1&; < C&D

/ 0 12 3 8 6 7 7 08 9 : 1&; <)= > ? <@ A <: > < 2 E 0 A F >HG

: 1&; <)= > ? <@ A <: > < 2 B 1&; < C&D

I 35J D

J K 4 6 7 7 0 8 9 : 1; < 0 L 9 I C C D 3 0 ?M 3

J K 8 6 7 7 0 8 9N G : 1&; < 0 L 9 I C C&D

You should always remember to check if a call to a memory allocation function was successful.

Page 8: Advanced Use of Pointers - UNB · 2004-02-17 · Outcomes: Advanced use of Pointers fiC for Java Programmersfl, Chapter 8, section 8.11, 8.15 Other textbooks on C on reserve After

Dynamic Memory Allocation

O�P Q R�S T

U R V WX YZ [ Q Y \ Q Y] ^ Y P ^ OP Q R U

O _` ` S a bc X X YZ ` \ O�d ^ Y _ ` OP Q e e e a a fg h h e

^i O Q ` jk lm n o V l h g p j e T

R S a q r T

O�P Q R�s T

U R c WX YZ [ Q Y \ Q Y] ^ t OP Q \ R U

O _` ` s a bc X X YZ ` t R \ O�d ^ Y _` OP Q e e e a a fg h h e

^i O Q ` jk lm n o V l h g p j e T

R s a u T5

s

Page 9: Advanced Use of Pointers - UNB · 2004-02-17 · Outcomes: Advanced use of Pointers fiC for Java Programmersfl, Chapter 8, section 8.11, 8.15 Other textbooks on C on reserve After

Dynamic Memory Allocation

v Note that malloc returns void*, whereas the left hand side of w x yz { { | } ~ � �&� � | � ~ � � � � �

is of type � � � �

. Some programmers use an explicit cast, but this is not required:

� � �� � � � ��� � � ��� � ��� � � � � � � � � � � � �

v Always pass ��� � | � ~ ��� w � �

as a parameter to malloc, rather than the absolute value

� use yz { { | } ~ � �� � | � ~ � � � � �

instead of yz { { | } ~� �

Page 10: Advanced Use of Pointers - UNB · 2004-02-17 · Outcomes: Advanced use of Pointers fiC for Java Programmersfl, Chapter 8, section 8.11, 8.15 Other textbooks on C on reserve After

Memory Deallocation

Memory should be deallocated once the task it was allocated for has been completed.

��� �  �¡ ¢

� £¤ ¤ ¡ ¥ ¦§ ¨ ¨�© ª ¤ « ��¬ ­ © £ ¤ �� � ® ® ® ¥ ¥ ¯° ± ± ®

­² � � ¤ ³´ µ¶ · ¸¹ µ ± ° º ³ ® ¢

  ¡ ¥ » ¼ ¢

½ ½ ½£�¾ ­ ­ ¤ ¡ ® ¢

¿ À ÁÂ Ã Ä Å Æ ÁÇ È É&Ê É Â Á Ë Ã Ì Í È ¿ À ¿

Page 11: Advanced Use of Pointers - UNB · 2004-02-17 · Outcomes: Advanced use of Pointers fiC for Java Programmersfl, Chapter 8, section 8.11, 8.15 Other textbooks on C on reserve After

Memory Deallocation

Always follow the call to

Î Ï Ï Ð Ñ

with

Ò Ó Ô Ô

Page 12: Advanced Use of Pointers - UNB · 2004-02-17 · Outcomes: Advanced use of Pointers fiC for Java Programmersfl, Chapter 8, section 8.11, 8.15 Other textbooks on C on reserve After

Errors

Õ Memory deallocation using

Ö&× Ø Ø ÙÚ

should only be used if memory has been previously allocated with ÛÜ Ý Ý Þ ß ÙÚ

:

à�á â àäã å�æ ç

æ è é à ç

ê�ë ì ì í æ î ç

ï always remember where memory came from: heap or stack

ð Don't create garbage objects!

ñ ò óô õ õ�ö ÷ ø�ù ú�û ü ö ý ø ú�þ ÿ � ���

ñ ò óô õ õ�ö ÷ ø�ù ú�û ü ö ý ø ú�þ ÿ � ���

� The first object created is now inaccessible

Page 13: Advanced Use of Pointers - UNB · 2004-02-17 · Outcomes: Advanced use of Pointers fiC for Java Programmersfl, Chapter 8, section 8.11, 8.15 Other textbooks on C on reserve After

Errors

� Given two pointers � and �, the assignment � � does not copy the block of memory pointed to by into a block of memory pointed to by �

� Remember that after � �; � and � share the value; if you call

��� � � ��� �

this would also deallocate �, now you must not call

��� � � ���

Page 14: Advanced Use of Pointers - UNB · 2004-02-17 · Outcomes: Advanced use of Pointers fiC for Java Programmersfl, Chapter 8, section 8.11, 8.15 Other textbooks on C on reserve After

Pointers to Blocks Containing Pointers

! A block containing three pointers to double objects. In order to access a single object, the code has to apply dereferencing twice

2.1

3.1

4.1

block

Page 15: Advanced Use of Pointers - UNB · 2004-02-17 · Outcomes: Advanced use of Pointers fiC for Java Programmersfl, Chapter 8, section 8.11, 8.15 Other textbooks on C on reserve After

Pointers to Blocks Containing Pointers

"$# % &' ( ) ) &' # * +-,. " ( /0 1 ( 23 45 6

0 /7 7 &' # * +98 *: ' ' # * 7 2 3 4 5 ; < 0 = ( # /7 "$# % &' ( ) > > >

8 8 ?@ A A >BC C D C E

FHG I JK L MON K P QR ST N K U U V

K F J JW X G Y Z[ K \ L Y] X X G Y J^ _ `K a b G F J c G dW X b V V V

L L ef g g V

hi i j i k

l m l no pq rs t uwv x kno p q ry z { y z { t uwv x k

Page 16: Advanced Use of Pointers - UNB · 2004-02-17 · Outcomes: Advanced use of Pointers fiC for Java Programmersfl, Chapter 8, section 8.11, 8.15 Other textbooks on C on reserve After

Pointers to Blocks Containing Pointers

The complete code to initialize the block:|�} ~ �� � ��� � � �� �� � � � � �

�� } � �� � � � � � � �� � � � �To free memory :

��� � �� � ��� � � ��  ¡ � � ¢ ¢ £

� �¤ ¤ �¥ ¦ � § ¨© � ª £ �

� � ¤ ¤ �¥ ¦ � § ¨ £ �

¥ ¦ � § ¨ � «¬ ­ ­�

Page 17: Advanced Use of Pointers - UNB · 2004-02-17 · Outcomes: Advanced use of Pointers fiC for Java Programmersfl, Chapter 8, section 8.11, 8.15 Other textbooks on C on reserve After

® ¯±° ²³ ´° µ¶ ·¸ ¹ º» ¼¾½ ³ ¿ ´À Á  ¿½ Ã Â±Ä Å Æ Ä ² Ç° ÇÄ ½ È » º

³ ²É É Ã Â Ä Å ÆËÊ Å ¿ Â Â Ä Å É µ ¶ ·¸ Ì Í ³ Î ° Ä ² É ¯ Ä Á à  ° » Ï Ï Ï Ê Ê ÐÑ Ò Ò Ï

ÓÔ Ô ÕÔ

Ö�× Ø ÙÚ Û ÜÞÝ Ú ß àá âã Ý Ú ä ä å

Ú Ö Ù Ùæ ç × è éê Ú ë Û èì ç ç × è ÙÚ ä íïî ðÚ ñ ò × Ö Ùó × ôæ ç ò å å å Û Ûõö ÷ ÷ åøù ùú ù

ûü ýþ ÿ � ��� � ÿ ��� þ � ü û

� ý � � � �� � � �� �� � ��� � � ûü ý þ ÿ� � ý � ü û

� ý �� � � � � � �� � � � �

� � � � ÿ � �� � � � � � � � !" �# " � # � $ � % �

&' ' ( '

)* +, - . / 0�1 23 4 * )

+�5 6 7 , 8 9;: 23 4 8 9�< , = >? @A < , B B C

+�5 6 7D 8 9< D = 8 , < D B B C

23 4 B 8 EF 5 G HI , J I D J <

Page 18: Advanced Use of Pointers - UNB · 2004-02-17 · Outcomes: Advanced use of Pointers fiC for Java Programmersfl, Chapter 8, section 8.11, 8.15 Other textbooks on C on reserve After

Pointers to Functions

K A pointer to a function determines the prototype of this function, but it does not specify its implementation:

L�M N OP Q�R S OT UV WX Y S�Z [P \ R U L�M N Y] N U \ QV M ^ N L U M P [

L�M N P Q R OT UV W X Y SZ [P \ QV M ^ N L U M ] Y N V ] M L�M _ ` ` ` P [

a You can assign an existing function to the pointer as long as both have identical parameter lists and return types:

b�c d ef g�h i jk l m�n op qc h d r ls e ic t d b h c p o

e�u v en

w You can call the function

xy z

through the pointer

{}| :

~�� � ~ � ��� �� � � ���

Page 19: Advanced Use of Pointers - UNB · 2004-02-17 · Outcomes: Advanced use of Pointers fiC for Java Programmersfl, Chapter 8, section 8.11, 8.15 Other textbooks on C on reserve After

Functions as Parameters

� � �� ��� ��� �� ��� � � �� � �� � �� � � �� � �� � ��� � �

� �� � �� � ��� � � � �� � �� �� �� � � �� � �� � � �

� �� � ��  ¡

� �¢ �   £ � �� ¡   ¤ £ � � � �¡   ¥ £ � ��� � �

�¢ ��¦ � � �§ ¨© ª;« ¬ � ¨­ ®« © ® �¯ ¦ § �   � � �   � � ¡

°� �� � �� � � � © � � �� � ��   � �

¢ � � � ¢ ¦   ¥ ­ ¡

°��� ��� �� �� �²± © « ® � © « ® � ®« ® © � � � � © � ¡

Page 20: Advanced Use of Pointers - UNB · 2004-02-17 · Outcomes: Advanced use of Pointers fiC for Java Programmersfl, Chapter 8, section 8.11, 8.15 Other textbooks on C on reserve After

Functions as Parameters

³ ´ µ¶ ·�¸ ¹�º »¸ ·�¼ ½ ¶ ´º ¹ »¼ » ´¾ ¿ ¶ ´º ¹ »¼ À µ�Á À ¿

¶ ´º ¹ »¼  ·�¼ à ¿ ¶ ´º ¹ »¼ ½Ä ÅÆ ½ ¶ ´º ¹ »¼ Æ Æ Ç

È

is called:– a virtual function; its implementation is not known to ÉËÊ Ì}Í ÎÊ ÉËÏ ÐÑ

but will be provided when ÒËÓ Ô}Õ ÖÓ ÒË× ØÙ

is called.

– a callback function, because it calls back the function supplied by the client.

Page 21: Advanced Use of Pointers - UNB · 2004-02-17 · Outcomes: Advanced use of Pointers fiC for Java Programmersfl, Chapter 8, section 8.11, 8.15 Other textbooks on C on reserve After

Generic Search

C does not support polymorphic programming, but it can besimulated using generic pointers (i.e. Ú Û ÜÝ Þ

). A function prototype may specify that a block of memory

and the value it is looking for are not typed:

ß�à á âã äå æ çè ã à é æê à â á ëê ßì í îï ê æ ðòñ

â ß�ó ã ô á â ß�ó ã ñ ëê ßì í ë äï õã ö�÷

ø í à ê à ù áûú üã ì ë äï õã âý þã ã ì ÿê å ã ü äå ä ÿã á ã å â ý í ø

ß�à á âã äå æ çè ã à é æê à â á ëê ßì í îï ê æ ðòñ â ßó ã ô á â ßó ã ñ

ëê ß ì í ë äï õã ñ ß�à á é í æê ÿ ü ä å ã ö é æê à â á ëê ß ì í ñ

æê à â á ëê ß ì í ö ö�÷

Page 22: Advanced Use of Pointers - UNB · 2004-02-17 · Outcomes: Advanced use of Pointers fiC for Java Programmersfl, Chapter 8, section 8.11, 8.15 Other textbooks on C on reserve After

Implementation of Generic Search (incorrect)

��� � �� �� � � � � �� � � � � �� � �� � � ���

� ��� � �� � ��� � � � �� � �� �� ���� � � � �� �� � � � � � �� � � � � �� � � �� � � � � �� � � � �

� �� � � �

� � � �� � � � � � ! " " �

� � � �� � # �

�� � � � � �� � � � � � $ �� � � �&% � �� � � � % % �

� � � �� �� �� � � � � �� �� � �

� � � �� � ' �

� � � �� � # �

(

Page 23: Advanced Use of Pointers - UNB · 2004-02-17 · Outcomes: Advanced use of Pointers fiC for Java Programmersfl, Chapter 8, section 8.11, 8.15 Other textbooks on C on reserve After

Implementation of Generic Search

)�* + ,- ./ 0 12 - * 3 04 * , + 54 )6 7 89 4 0 :�;

, )�< - =+ , )�< - ; 54 )6 7 5 .9 >- ; , )< - =+ - 9 ? )< - ;)�* + 3 7 04 @A . / - B 3 04 * , + 54 )6 7 ; 0 4 * , + 54 )6 7 B B C

54 )6 7 A D

) E 3 89 4 0 : F F GH I I B

/ - + >/ * J D

E4 / 3 A F 89 4 0 : D A K 89 4 0 : L , )< - 7 - 9 ? )< - D A L F

- 9 ? )< - B

) E 3 04 @A ./ - 3 A ; 5 .9 >- B B

/ - + >/ * M D

/ - + >/ * J D

N

Page 24: Advanced Use of Pointers - UNB · 2004-02-17 · Outcomes: Advanced use of Pointers fiC for Java Programmersfl, Chapter 8, section 8.11, 8.15 Other textbooks on C on reserve After

Application of Generic Search

The client's responsibilities:

O�P Q RS TU V RS P W Q XS Y Z[ \ ]_^ ` RS P W Q XS Y Z[ \ ]_a b c

d \ Q Y dP ] ^ e e ] a f

gO�P Q RS TU V RS P W Q hS O X ]^ ` RS P W Q hS O X ]_a b c

d \ Q Y dP ] V XS Y Z[ \ ] b ^ e e ] V XS Y Z [ \ ] b a f

g

Note that this callback is sufficient for search, but not for sort.

Page 25: Advanced Use of Pointers - UNB · 2004-02-17 · Outcomes: Advanced use of Pointers fiC for Java Programmersfl, Chapter 8, section 8.11, 8.15 Other textbooks on C on reserve After

ij kml l no pq r o st s u q vw t w x o p y w q x p z j i

{ | w uo t w }~ �� � �

| s� � n w j ���

| s� � n w � � � �� � � �

o t r o �

o u� � � � �q n n s p � }~ �� j y o � w s u � | s � � n w � � � � � �� � � �

w �o r � � �~ ��

� k~ � � �� � �

u s x � o � � � o � }~ �� � o � � � ij o t o r o q no � w j i

o u � y p q t u � �� n u ��� � �� o   � ¡ � � � ¢

u x w w � � � �

w �o r � � �~ ��

� k~ � � �� � �

£

l xo t r u � �� u ¤q y � y st w s u r z w �q n� w y ¥t � �

�� y w q x p z¦ w t � �� } ~ �� � � �� y o � w s u � | s � � n w �� p s �l �

� � � § � � ¨ � t s r � � �

Page 26: Advanced Use of Pointers - UNB · 2004-02-17 · Outcomes: Advanced use of Pointers fiC for Java Programmersfl, Chapter 8, section 8.11, 8.15 Other textbooks on C on reserve After

NAME qsort – sorts an array

SYNOPSIS #include <stdlib.h>

void qsort(void *base, size_t nmemb, size_t size, int(*compar)(const void *, const void *));

DESCRIPTION The qsort() function sorts an array with nmemb elements of size size. The base argument points to the start of the array.

The contents of the array are sorted in ascending order according to a comparison function pointed to by compar, which is called with two arguments that point to the objects being compared.

The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respec- tively less than, equal to, or greater than the second. If two members compare as equal, their order in the sorted array is undefined.