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

Slides:



Advertisements
Similar presentations
Dynamic memory allocation
Advertisements

Dynamic Memory Allocation in C.  What is Memory What is Memory  Memory Allocation in C Memory Allocation in C  Difference b\w static memory allocation.
Various languages….  Could affect performance  Could affect reliability  Could affect language choice.
CS1061: C Programming Lecture 21: Dynamic Memory Allocation and Variations on struct A. O’Riordan, 2004, 2007 updated.
ECE Application Programming Instructor: Dr. Michael Geiger Fall 2012 Lecture 31: Dynamic memory allocation.
Spring 2005, Gülcihan Özdemir Dağ Lecture 12, Page 1 BIL104E: Introduction to Scientific and Engineering Computing, Spring Lecture 12 Outline 12.1Introduction.
CSCI 171 Presentation 11 Pointers. Pointer Basics.
1 Memory Allocation Professor Jennifer Rexford COS 217.
Pointer applications. Arrays and pointers Name of an array is a pointer constant to the first element whose value cannot be changed Address and name refer.
Kernighan/Ritchie: Kelley/Pohl:
Memory allocation CSE 2451 Matt Boggus. sizeof The sizeof unary operator will return the number of bytes reserved for a variable or data type. Determine:
POINTER Prepared by MMD, Edited by MSY1.  Basic concept of pointers  Pointer declaration  Pointer operator (& and *)  Parameter passing by reference.
Dynamic memory allocation. The process of allocating memory at run time is known as dynamic memory allocation. C have four library functions for allocating.
Programming III SPRING 2015 School of Computer and Information Sciences Francisco R. Ortega, Ph.D. McKnight Fellow and GAANN Fellow LECTURE #5 More about.
1 Pointers A pointer variable holds an address We may add or subtract an integer to get a different address. Adding an integer k to a pointer p with base.
1 Day 03 Introduction to C. 2 Memory layout and addresses r s int x = 5, y = 10; float f = 12.5, g = 9.8; char c = ‘r’, d = ‘s’;
Memory Arrangement Memory is arrange in a sequence of addressable units (usually bytes) –sizeof( ) return the number of units it takes to store a type.
Rossella Lau Lecture 8, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 8: Polymorphism & C++ pointer  Inheritance.
C and Data Structures Baojian Hua
1 CSE 303 Lecture 11 Heap memory allocation ( malloc, free ) reading: Programming in C Ch. 11, 17 slides created by Marty Stepp
CSc 352 C : Arrays, Structs, Pointers
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
Memory Layout C and Data Structures Baojian Hua
Pointers Applications
1 Procedural Concept The main program coordinates calls to procedures and hands over appropriate data as parameters.
Arrays and Pointers in C Alan L. Cox
Pointer Data Type and Pointer Variables
CS 11 C track: lecture 5 Last week: pointers This week: Pointer arithmetic Arrays and pointers Dynamic memory allocation The stack and the heap.
17. ADVANCED USES OF POINTERS. Dynamic Storage Allocation Many programs require dynamic storage allocation: the ability to allocate storage as needed.
1 C - Memory Simple Types Arrays Pointers Pointer to Pointer Multi-dimensional Arrays Dynamic Memory Allocation.
Stack and Heap Memory Stack resident variables include:
Dynamic Memory Allocation The process of allocating memory at run time is known as dynamic memory allocation. C does not Inherently have this facility,
David Notkin Autumn 2009 CSE303 Lecture 12 October 24, 2009: Space Needle.
Computer Science and Software Engineering University of Wisconsin - Platteville 2. Pointer Yan Shi CS/SE2630 Lecture Notes.
1 Pointers Arrays have a disadvantage: Their size must be known at compile time. We would like the capability to allocate an array-like object of any needed.
ECE 103 Engineering Programming Chapter 47 Dynamic Memory Alocation Herbert G. Mayer, PSU CS Status 6/4/2014 Initial content copied verbatim from ECE 103.
Dynamic Memory Allocation. Domain A subset of the total domain name space. A domain represents a level of the hierarchy in the Domain Name Space, and.
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.
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes.
Copyright 2005, The Ohio State University 1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation.
Pointers in C Computer Organization I 1 August 2009 © McQuain, Feng & Ribbens Memory and Addresses Memory is just a sequence of byte-sized.
ECE Application Programming
12/23/2015Engineering Problem Solving with C++, second edition, J. Ingber 1 Engineering Problem Solving with C++, Etter/Ingber Chapter 9 An Introduction.
© Janice Regan, CMPT 128, February CMPT 128: Introduction to Computing Science for Engineering Students Pointers.
1 Lecture07: Memory Model 5/2/2012 Slides modified from Yin Lou, Cornell CS2022: Introduction to C.
1 Recall that... char str [ 8 ]; str is the base address of the array. We say str is a pointer because its value is an address. It is a pointer constant.
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
MORE POINTERS Plus: Memory Allocation Heap versus Stack.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 11: Pointers.
BIL 104E Introduction to Scientific and Engineering Computing Lecture 9.
DYNAMIC MEMORY ALLOCATION. Disadvantages of ARRAYS MEMORY ALLOCATION OF ARRAY IS STATIC: Less resource utilization. For example: If the maximum elements.
Arrays and Pointers (part 1) CSE 2031 Fall July 2016.
CSE 220 – C Programming malloc, calloc, realloc.
Dynamic Allocation in C
Object Lifetime and Pointers
Stack and Heap Memory Stack resident variables include:
Pointers.
Day 03 Introduction to C.
Checking Memory Management
Lecture 6 C++ Programming
Pointers, Dynamic Data, and Reference Types
CSC215 Lecture Memory Management.
Dynamic Memory Allocation
Memory Allocation CS 217.
Pointers.
EECE.2160 ECE Application Programming
Dynamic Memory Allocation (and Multi-Dimensional Arrays)
Pointers The C programming language gives us the ability to directly manipulate the contents of memory addresses via pointers. Unfortunately, this power.
Dynamic Memory – A Review
Module 13 Dynamic Memory.
Presentation transcript:

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

 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 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)

 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];

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

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

 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

 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

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

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

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

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

 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’

 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

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.

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()

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.

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.

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

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

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.

 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

 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

 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

 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

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 */ }

 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 */ }

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 */ }

 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

 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