Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Prachi A. Joshi Assistant Professor in CSE DIEMS,Aurangabad Unit 1 : Basic Concepts Pointers and dynamic memory allocation, Algorithm Specification, Data."— Presentation transcript:

1 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

2  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 C2

3 3 No bounds checking! Allowed – usually causes no error array[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)

4  Homogeneous  Each element same size – s bytes ◦ An array of m data values is a sequence of m  s bytes ◦ Indexing: 0 th value at byte s  0, 1 st value at byte s  1, …  m and s are not part of representation Pointers in C4 a[0] a[1] a[2] 0x1000 0x1004 0x1008 int a[3];

5 What is  sizeof(array[3])?  sizeof(array)? Pointers in C5 int array[10]; 4 40 returns the size of an object in bytes

6 Pointers in C6 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

7  Pointers are fundamental to C.  C provides extensive support for pointer.  Example : int i, *pi; pi=&i; Pointers in C7 & : Address Operator * : Dereferencing or Indirection operator

8  Creation & variableReturns variable’s memory address  Dereference pointerReturns contents stored at address  Indirect assignment * pointer = valStores value at address  Assignment pointer = ptrStores pointer in another variable Pointers in C8

9 pointer + numberpointer – number E.g., pointer + 1 adds 1 something to a pointer Pointers in C9 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

10  Special constant pointer NULL ◦ Points to no data ◦ Dereferencing illegal – causes segmentation fault ◦ To define, include or Pointers in C10

11 Pointers in C11 void 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

12 Pointers in C12 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

13  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 C13 char str1[15] = “Hello, world!\n”; char *str2 = “Hello, world!\n”; Hello,wlord!\n length Hello,wlord!\n terminator Pascal, Java, … C, … C terminator: ’\0’

14  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. Pointers in C14

15 Pointers in C15 Static Memory AllocationDynamic 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 heapsImplemented using data segments. Pointer is needed to accessing variables. No need of Dynamically allocated pointers. Faster execution than DynamicSlower execution than static More memory Space required.Less Memory space required.

16 Pointers in C 16 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()

17 Pointers in C 17 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.

18 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.

19 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));

20 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));

21 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.

22  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 C22

23  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 C23 Output : Any address Garbage Value

24  Dangling pointers and wild pointers in computer programming are pointers that do not point to a valid object of the appropriate type.computer programmingpointers  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.object destruction  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).dereferences unpredictable behaviorbugssegmentation faultsgeneral protection faults Pointers in C24

25  Dangling pointers and wild pointers in computer programming are pointers that do not point to a valid object of the appropriate type.computer programmingpointers  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.object destruction  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).dereferences unpredictable behaviorbugssegmentation faultsgeneral protection faults Pointers in C25

26 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“. Pointers in C26 #include { char *ptr = malloc(Constant_Value);....... free (ptr); /* ptr now becomes a dangling pointer */ }

27  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“. Pointers in C27 #include { char *ptr = malloc(Constant_Value);....... free (ptr); /* ptr now becomes a dangling pointer */ ptr = NULL /* ptr is no more dangling pointer */ }

28 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” Pointers in C28 #include void main( ) { char *ptr = NULL;..... { char ch; ptr = &ch; }..... /* ptr is now a dangling pointer */ }

29  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.memory (2) In computer science, a memory leak occurs when a computer program incorrectly manages memory allocationscomputer sciencecomputer programmemory allocations Pointers in C29

30  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 in C30


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

Similar presentations


Ads by Google