Presentation is loading. Please wait.

Presentation is loading. Please wait.

C Programming Day 4. 2 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 More on Pointers Constant Pointers Two ways to.

Similar presentations


Presentation on theme: "C Programming Day 4. 2 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 More on Pointers Constant Pointers Two ways to."— Presentation transcript:

1 C Programming Day 4

2 2 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 More on Pointers Constant Pointers Two ways to understand it 1.const data_type *var; –pointer to constant integer 2.data_type *const var; –constant pointer can not get its value changed –must continue to point to var throughout the execution Examples: int i=0; const int *pci; /* Pointer to a constant integer */ int *const cpi = &i; /* Constant Pointer to an integer */

3 3 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 More on Pointers… Pointers and Arrays /* Array Declaration */ int a[5]; a is a constant pointer = &a[0] a[0] a[1] a[2] a[3] a[4] *a *(a+1) *(a+2) *(a+3) *(a+4)

4 4 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 More on Pointers… int a[5]={0,1,2,3,4}; int *pa; pa=a; pa = pa + 3; printf(“%d %d\n”,*pa, a[3]); pa+3 pa + 3 *(sizeof(int))

5 5 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 More on Pointers… Pointer Arithmetic –Valid operations Assignment of 0(or NULL) to a pointer Addition or subtraction of an integer to a pointer Subtractions of two pointers pointing to the members of same array Comparing a pointer to NULL –Invalid operations Assignment of a nonzero integer to pointer Addition, multiplication, division of two pointers Comparisons of two pointers that do not point to the same members

6 6 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 More on Pointers… Function returning a pointer –Useful to return a string or an array Example: /*********************************************** * Function Name: compstr * Description: Compares two strings and returns * the string which is lexicographically higher * Input: char *, char * * Output: char * ***********************************************/ char* compstr(char *pcString1, char *pcString2) { int iLex = 0; iLex=strcmp(pcString1, pcString2); if (iLex < 0) return pcString2; if (iLex > 0) return pcString1; if (iLex == 0) return pcString1; }

7 7 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 Function Pointer A function pointer is a pointer variable When the compiler compiles a program it creates the entry point for each function in the program A function pointer contains the address of the entry point of a function The entry point is the address to which execution transfers when a function is called

8 8 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 Function Pointer… Declaring a function pointer –int add(int, int); function accepts 2 integers and return a integer –int (*pAdd)(int, int); pAdd is a pointer to a function which can only point to those functions which accept 2 integers and return a integer –pAdd=Add; Assign the address of add to pAdd –pAdd(10,20); call to add() function using pointer to function

9 9 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 Function Pointer… Passing function pointers as arguments to a another function –The function to which the pointer is passed will call the function using the pointer variable and not the function name Prototype of a function which accepts a function pointer Example –void F(void (*pf) (int) ); –The function pointer can point to any function which accepts an integer and returns a void

10 10 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 Function Pointer… Declaring a array of function pointers –int Add (int, int); function Add accepts 2 integers and return a integer –int Sub (int, int); function Sub accepts 2 integers and return a integer –int (*pf[4])(int, int); pf is a array of pointers to a functions

11 11 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 Function Pointer… Initializing the array elements with functions addresses. –pf[0]=Add; Assign the address of Add() to the zero th element of the array –pf[1]=Sub; Assign the address of Sub() to the first element of the array Calling the functions using function pointers stored as array elements –int result = pf[0](10,20); This statement will call function Add() –int result = pf[1](10,20); This statement will call function Sub()

12 12 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 Dynamic 2D Arrays A 2D array of size M *N –It is a collection of M 1D arrays, –each array of size N. –M is the number of rows and N is the number of columns in the 2D array Allocating 2D arrays, of size M*N at runtime needs to be done in 2 steps. 1.Allocate an array of size M using malloc(), –which will be used in step 2. –Store the base address of this array in a pointer variable. –This will act as the array name. 2.Allocate M one dimensional arrays each of size N using malloc() –store their base addresses in the array allocated in step 1

13 13 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 Dynamic 2D Arrays… Illustration of dynamic creation of a 2D array

14 14 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 Dynamic 2D Arrays… Once the 2D array is allocated its elements can be accessed using the usual notation –To use the 2 nd element in the 2 nd row of a 2D array (array name ‘a’) a[2][2]=10

15 15 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 Dynamic 2D Arrays… Releasing 2D arrays, of size M*N at runtime needs to be done in in the reverse order i.e. –Release the M one dimensional arrays each of size N using free() –Release the array of size M using free(), which was used to store the base address for each row

16 16 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 Need For Pointers Pass information to functions and return information from functions. –A variable declared within a function cannot be accessed in some other function To achieve this the caller function needs to pass the address of the variable to the called function A function can return only one value at a time. Incase we need to return multiple values to the caller function, the caller function should pass the address of variables declared in it so that the called function can write to these variables serving the purpose of multiple return values to the calling environment.

17 17 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 Need For Pointers… Storing addresses of functions. –In certain situations we need to pass functions as arguments to another function. –This can be achieved by passing the address of the function. Dynamic Memory allocation. –If memory is allocated at runtime its starting address need to stored in the program so that we can access the entire memory based on its starting address.

18 18 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 Golden Rules of Memory Management Never use uninitialized memory Never allocate Memory Twice Never deallocate Twice Never use deallocated memory Never dereference a NULL pointer Never return address of local variable Deallocate memory after its use (to avoid memory leaks) Check whether storage is freed on all possible cases of input Check for memory overwritten errors

19 19 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 Golden Rules of Memory Management… Check for destination storage size before copying Check for array index within bounds Check whether memory allocation has succeeded before using the memory block Always end the strings with null terminator when you are allocating strings Check number of bytes allocated is appropriate for the type Avoid creating garbage and dangling pointers Check always input to the scanf function is an address that is valid Don’t try to free memory area allocated by the compiler (The area that the programmer has not allocated)

20 20 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 Violation of golden rules What is the problem with the code given below ? int *p= (int*) malloc(100*sizeof(int)) ; p=(int*) malloc(50*sizeof(int)); Answer It allocates a block of 100 integers and p is pointing to it and without freeing that p is made to point to another block of 50 integers.So first allocated block becomes GARBAGE (TBD: Fix here) Rule violated Never allocate Twice without (TBD: Rephrase) freeing the memory already allocated Remedy Before allocating the second block free the space occupied by first block int *p=(int*)malloc(100*sizeof(int)); free(p); p=(int*) malloc(50*sizeof(int));

21 21 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 What is the problem in the code given below ? int *p = (int*) malloc(sizeof(int)*100); p=NULL; Answer The code allocates a block of 100 integers and without freeing that makes p to NULL that means the block of 100 integers becomes a garbage Violated Rule Free memory after usage and don’t create garbage Remedy int *p = (int*) malloc(sizeof(int)*100); free(p); p=NULL; Violation of golden rules…

22 22 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 What is the problem with the code given below ? int *p; *p=20 Answer p is not initialized so it contains a garbage value so assignment to the location pointed by p will make system crash Violated Rule Never use uninitialized pointers Violation of golden rules…

23 23 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 What is the problem with the code given below? int size; Int *arr; Printf(“\n Enter size of the array”); Scanf(“%d”,&size); arr=(int*)malloc(size); for(int i=0;i<size;i++) Arr[i]=I; Answer The code did not allocate enough number of bytes it has allocated just size bytes,but it should have allocated size *sizeof(int) bytes. Violated Rules Allocate proper number of bytes needed and trying to access unallocated area Remedy In the allocation statement it should be changed like Arr=(int*) malloc(Size*sizeof(int)); Violation of golden rules…

24 24 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 What is the error in the code given below? Int *p =(int*) malloc(10*sizeof(int)); ….. …. Free(p); …. … Free(p); Answer Trying to deallocate twice Violated rule Never deallocate twice Violation of golden rules…

25 25 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 What is the error in the code given below? Int *p=(int*) malloc(10*sizeof(int)); …… Free(p); ….. P[2]=25; Answer Trying to use a memory region that is deallocated Violated rule Never use deallocated memory Violation of golden rules…

26 26 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 What is the error in the code given below? Char *str=“hello world”; …. Free(str); Answer Trying to free memory allocated by compiler Violated Rule Never try to deallocate memory allocated by compiler Violation of golden rules…

27 27 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 What is the error in the code given below? char *str="hello world"; ….. …. strcpy(str,"hai "); Answer Trying to assign to a pointer to a constant string Violated rule Never assign to constant pointers Violation of golden rules…

28 28 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 What is the error in the code given below? Int x; Scanf(“%d”,x); Answer The input parameters to scanf must be an address Violated Rule Trying to assign to an unknown location Violation of golden rules…

29 29 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 What is the error in the code given below? Int* f(int x) { int y=-x; return &y; } Answer Trying to return address of local variable Violated rule Space for local variable gets deallocated and its address is invalid after function returns Violation of golden rules…

30 30 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 What is the problem with the code given below? Int *p=(int*) malloc(sizeof(int)*10); Int *p1=p; …. … Free(p); ….. P1[2]=20; Answer The above code creates a dangling pointer that is p1 is pointing to a block that is already freed. Violated Rule Never create a dangling pointer. Never use deallocated memory Violation of golden rules…

31 31 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 What is the problem with the code given below? Int *arr; …. … Arr[2]=4; Answer The problem here is the lack of understanding of arrays and pointers. Trying to access a pointer like an array. Violated Rules Never use unallocated memory Violation of golden rules…

32 32 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 What is the error in the code given below ? char str1[10]; strcpy(str1,"hello world is great and really good "); Answer Trying to overwrite beyond the allocated string Violation of golden rules…

33 33 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 What is the error in the code given below? Int *p=(int*) malloc(sizeof(int)*10); For(int i=0;i<10;i++) *(p+i)=i; Answer The given code visits memory that is not part of the array (array index out of bounds,run time error) Violation of golden rules…

34 34 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 What is the error in the code given below? int** table = (int**) malloc(10 *sizeof(int*)); int i, j; for(i =0; i < size; i++) { table[i] = (int*) malloc(10 * sizeof(int)); } free(table); for (i = 0 i < size; i++) { free(table[i]); } Answer After freeing the array of pointers trying to free the individual pointers. Violation of golden rules…

35 35 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 What is the error in the code given below? Struct my { int *p; int *p1; }; Struct my *p2=(struct my*)malloc(sizeof(struct my)); P2->p=(int*)malloc(sizeof(int)); P2->p1=(int*)malloc(sizeof(int)); free(p2); Answer Failure to free memories pointed by pointers those are members of the structure. Remedy Free the individual structure elements before freeing the entire structure Violation of golden rules…

36 36 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 What is the error in the code given below? int check_palindrome(char *str) { char *str1=(char*)malloc(strlen(str)+1); Strcpy(str1,str); Str1=strrev(str1); return strcmp(str1,str)==0; } Answer Failure to free the space allocated from heap for str1 Violation of golden rules…

37 37 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 What is the error in the code given below? int check_if1(char *str) { char *str1=(char*)malloc(strlen(str)); if(strcmp(str1,”1”)==0) return 1; else { free(str1); Return 0; } } Answer Did not free str1 if the input is the string “1” Violation of golden rules…

38 38 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 What is the error in the code given below? Int *ptr = (int*) malloc(sizeof(int)*10); … … Free(ptr+5); Answer Input to free must be a pointer to the block that is returned by malloc Violation of golden rules…

39 39 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 What is the error in the code given below? const int SIZE =100; int *arr[SIZE]; for(int i=0;i<SIZE;i++) { arr[i]=(int*)malloc(i*size); …..,,,,.. } Answer It may lead to memory leaks and heap may exhaust at the end of the loop Violated Rules 1.Check always allocation has succeeded 2.Don’t create a memory leak Violation of golden rules…

40 40 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 What is the error in the code given below? char* concatenate(char* str[],int size) { int totlen=0; int i; char *constr; for(i=0;i<size;i++) totlen +=strlen(str[i]); totlen++; constr = (char*) malloc(totlen+1); for(i=0;i<size;i++) strcat(constr,str[i]); return constr; } Answer Strcat needs the strings to be null terminated or else it will give unpredicatable results Violation of golden rules…

41 41 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 What is the error in the code given below? int *p=NULL; *p=20; Answer Trying to dereference a NULL pointer Violated Rule Never Dereference a NULL POINTER Violation of golden rules…

42 42 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 What is the error in the code given below? char *p=(char*)malloc(11); strcpy(p,"hello world"); Answer Allocates 11 bytes and overwrites it with 12 bytes (space for NULL terminator is not allocated) Violation of golden rules…

43 43 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 What is the error in the code given below? void test() { int* p1 = (int*) malloc(sizeof(int)); int* p2 = p1; *p1 = 1; eval(p1); free(p1); *p2 = 2; } Answer Writing to write to a location that is already freed Violation of rules Avoid creating dangling pointers Violation of golden rules…

44 44 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 What is the error in the code given below? void test() { char* str = (char*) malloc(10); x[10] = '\0'; } Answer Memory overwrite Violation of rule Allocate one more byte for string than needed Violation of golden rules…

45 45 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 What is the error in the code given below? int *ptr; …. Free(ptr); Answer Attempting to free a block which is never allocated Violation of golden rules…

46 46 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 What is the error in the code given below? int *p=NULL; int x=20; …. p=x; *p=40; Answer Instead of assigning the address of x the pointer is assigned to point to the value of x that is to address 20 so system will crash Violation of golden rules…

47 47 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 Thank You!


Download ppt "C Programming Day 4. 2 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 More on Pointers Constant Pointers Two ways to."

Similar presentations


Ads by Google