Programming in C Pointers and Arrays, malloc( ). 7/28/092 Dynamic memory In Java, objects are created on the heap using reference variables and the new.

Slides:



Advertisements
Similar presentations
Dynamic memory allocation
Advertisements

Lectures 10 & 11.
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.
Unions The storage referenced by a union variable can hold data of different types subject to the restriction that at any one time, the storage holds data.
What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
Programming in C Pointers and Arrays. 1/14/102 Pointers and Arrays In C, there is a strong relationship between pointers and arrays.In C, there is a strong.
CSCI 171 Presentation 11 Pointers. Pointer Basics.
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:
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.
Dynamic Data Structures H&K Chapter 14 Instructor – Gokcen Cilingir Cpt S 121 (July 26, 2011) Washington State University.
CS100A, Fall 1997, Lecture 241 CS100A, Fall 1997 Lecture 24, Tuesday 25 November (There were no written notes for lecture 23 on Nov. 20.) Data Structures.
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.
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
Pointers Applications
1 Procedural Concept The main program coordinates calls to procedures and hands over appropriate data as parameters.
Programming in C Pointers and Arrays. 1/14/102 Pointers and Arrays In C, there is a strong relationship between pointers and arrays.In C, there is a strong.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes.
Pointer Data Type and Pointer Variables
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes.
CS 11 C track: lecture 5 Last week: pointers This week: Pointer arithmetic Arrays and pointers Dynamic memory allocation The stack and the heap.
Chapter 17 Pointers and Arrays. Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Pointers and Arrays.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Tevfik Bultan Lecture 12: Pointers continued, C strings.
1 Programming with Pointers Turgay Korkmaz Office: SB Phone: (210) Fax: (210) web:
1 C - Memory Simple Types Arrays Pointers Pointer to Pointer Multi-dimensional Arrays Dynamic Memory Allocation.
CSC 2400 Computer Systems I Lecture 5 Pointers and Arrays.
C++ Programming: From Problem Analysis to Program Design, Second Edition1 Objectives In this chapter you will: Learn about the pointer data type and pointer.
Programming in C Advanced Pointers. Pointers to Pointers Since a pointer is a variable type, a pointer may point to another pointer.Since a pointer is.
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.
Current Assignments Start Reading Chapter 6 Project 3 – Due Thursday, July 24 Contact List Program Homework 6 – Due Sunday, July 20 First part easy true/false.
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes.
1 Pointers to structs. 2 A pointer to a struct is used in the same way as a pointer to a simple type, such as an int. Pointers to structs were introduced.
Copyright 2005, The Ohio State University 1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation.
19&20-2 Know how to declare pointer variables. Understand the & (address) and *(indirection) operators. Dynamic Memory Allocation Related Chapter: ABC.
CS 376b Introduction to Computer Vision 01 / 23 / 2008 Instructor: Michael Eckmann.
1 CMSC 202 Pointers Dynamic Memory Allocation. 2 A simple variable A variable is drawn as a labeled box int x; X :
Pointers in C Computer Organization I 1 August 2009 © McQuain, Feng & Ribbens Memory and Addresses Memory is just a sequence of byte-sized.
CSE 232: C++ memory management Overview of Arrays Arrays are the simplest kind of data structure –One item right after another in memory (“contiguous range”
Pointers *, &, array similarities, functions, sizeof.
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
1 Lecture07: Memory Model 5/2/2012 Slides modified from Yin Lou, Cornell CS2022: Introduction to C.
POINTERS Introduction to Systems Programming - COMP 1002, 1402.
Fall 2004CS-183 Dr. Mark L. Hornick 1 C++ Arrays C++ (like Java) supports the concept of collections – mechanisms to sort and manipulate many instances.
Copyright © 2014 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic Arrays.
CSE 332: C++ pointers, arrays, and references Overview of Pointers and References Often need to refer to another object –Without making a copy of the object.
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
1 Dynamic Memory Allocation. 2 In everything we have done so far, our variables have been declared at compile time. In these slides, we will see how to.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 11: Pointers.
Programming in C Pointers and Arrays. 1/14/102 Pointers and Arrays In C, there is a strong relationship between pointers and arrays.In C, there is a strong.
Chapter 16 Pointers and Arrays Pointers and Arrays We've seen examples of both of these in our LC-3 programs; now we'll see them in C. Pointer Address.
CS 31 Discussion, Week 7 Faisal Alquaddoomi, Office Hours: BH 2432, W 4:30-6:30pm, F 12:30-1:30pm.
Chapter 5 Pointers and Arrays Ku-Yaw Chang Assistant Professor, Department of Computer Science and Information Engineering Da-Yeh.
BIL 104E Introduction to Scientific and Engineering Computing Lecture 9.
You learned how to declare pointer variables how to store the address of a variable into a pointer variable of the same type as the variable how to manipulate.
DYNAMIC MEMORY ALLOCATION. Disadvantages of ARRAYS MEMORY ALLOCATION OF ARRAY IS STATIC: Less resource utilization. For example: If the maximum elements.
Programming in C Advanced Pointers.
Dynamic Allocation in C
Intro to Pointers in C CSSE 332 Operating Systems
Stack and Heap Memory Stack resident variables include:
Computer Organization and Design Pointers, Arrays and Strings in C
Motivation and Overview
Programming Languages and Paradigms
Pointers, Dynamic Data, and Reference Types
Memory Allocation CS 217.
Chapter 16 Pointers and Arrays
Programming in C Pointers and Arrays.
Programming in C Advanced Pointers.
Pointers, Dynamic Data, and Reference Types
SPL – PS2 C++ Memory Handling.
Presentation transcript:

Programming in C Pointers and Arrays, malloc( )

7/28/092 Dynamic memory In Java, objects are created on the heap using reference variables and the new operator. Memory is freed by the garbage collector. In C, memory is allocated from the heap using library functions malloc(), calloc(), and realloc(). These functions return a pointer to the allocated heap memory. Memory must be explicitly freed using free() to avoid memory leaks and program crashes. The argument to free( ) is a pointer returned when the memory is allocated.

7/28/093 Dynamic Memory Comparison In JAVA public class Person { public int age; public double gpa; } // memory allocation Person bob = new Person( ); bob.age = 42; bob.gpa = 3.5; // bob is eventually freed by // garbage collector In C typedef struct person { int age; double gpa; } PERSON; /* memory allocation */ PERSON *pbob = (PERSON *)malloc(sizeof(PERSON)); pbob->age = 42; pbob->gpa = 3.5;... /* explicitly freeing the memory */ free( pbob ); In C, note the use of malloc( ) instead of new free( ) -> (arrow) rather than. (dot)

7/28/094 Dynamic Memory Functions These functions are used to allocate and free dynamically allocated heap memory and are part of the standard C library void *malloc( size_t nrBytes ); –Returns a pointer to dynamically allocated memory on the heap of size nrBytes, or NULL if the request cannot be satisfied. The memory is uninitialized. void *calloc( int nrElements, size_t nrBytes ); –Same as malloc( ), but the memory is initialized to zero void *realloc( void *p, size_t nrBytes); –Changes the size of the memory pointed to by p to nrBytes. The contents will be unchanged up to the minimum of the old and new size. If the new size is larger, the new space is uninitialized. Returns a pointer to the new memory, or NULL if request cannot be satisfied in which case *p is unchanged. void free( void *p ) –Deallocates the memory pointed to by p which must point to memory previously allocated by calling one of the functions above. Does nothing if p is NULL.

7/28/095 void* and size_t The void* type is C’s generic pointer. It may point to any kind of variable (but may not be dereferenced). Any other pointer type may be converted to void* and back again without loss of information. void* is often used as parameter types to, and return types from, library functions.The void* type is C’s generic pointer. It may point to any kind of variable (but may not be dereferenced). Any other pointer type may be converted to void* and back again without loss of information. void* is often used as parameter types to, and return types from, library functions. size_t is an unsigned integral type that should be used (rather than int ) when expressing the size of “something” (e.g. an int, array, string, or struct). It too is often used as a parameter to, or return type from, library functions. size_t is defined as the type that is returned from the sizeof( ) operator.size_t is an unsigned integral type that should be used (rather than int ) when expressing the size of “something” (e.g. an int, array, string, or struct). It too is often used as a parameter to, or return type from, library functions. size_t is defined as the type that is returned from the sizeof( ) operator.

7/28/096 Pointers and Arrays In C, there is a strong relationship between pointers and arrays.In C, there is a strong relationship between pointers and arrays. –Any array operation that can be accomplished with subscripting (using [ ]) can also be done with pointers The declaration int a[10]; defines an array of 10 ints which is guaranteed to be a block of consecutive integers named a[0], a[1],... a[9]. The notation a[ i ] refers the “i-th” element of the array.The declaration int a[10]; defines an array of 10 ints which is guaranteed to be a block of consecutive integers named a[0], a[1],... a[9]. The notation a[ i ] refers the “i-th” element of the array. If p is defined as a pointer to an int, then the assignment p = &a[0]; sets p to point to the first element of the array. The assignment x = *p; will copy the contents of a[0] into x.If p is defined as a pointer to an int, then the assignment p = &a[0]; sets p to point to the first element of the array. The assignment x = *p; will copy the contents of a[0] into x.

7/28/097 More Pointers & Arrays Since the name of an array is a synonym for the address of the first element of the array, the statement p = &a[0]; is equivalent to p = a;Since the name of an array is a synonym for the address of the first element of the array, the statement p = &a[0]; is equivalent to p = a; If p points to a particular element of an array, then p + 1 points to the next element of the array and p + n points n elements after p, REGARDLESS of the type of the array.If p points to a particular element of an array, then p + 1 points to the next element of the array and p + n points n elements after p, REGARDLESS of the type of the array. The meaning a “adding 1 to a pointer” is thatThe meaning a “adding 1 to a pointer” is that p + 1 points to the next element in the array.

7/28/098 More Pointers and Arrays The expression a[ i ] can also be written as *(a + i). The two forms are equivalent. It follows then that &a[ i ] and (a + i) are also equivalent. (a + i ) is the address of the i-th element beyond a. On the other hand, if p is a pointer, then it may be used with a subscript. p[ i ] is identical to *(p + i). p[ i ] is identical to *(p + i). In short, an array-and-index expression is equivalent to a pointer-and-offset expression.

7/28/099 Pointer Arithmetic Note in the last slide that no mention was made of the type of the array. Why not? Because it DOESN’T MATTER!Note in the last slide that no mention was made of the type of the array. Why not? Because it DOESN’T MATTER! If “” is an array of ints, then is the k-th int and so isIf “ a ” is an array of ints, then a[ k ] is the k-th int and so is *(a + k). If “” is an array of doubles, then is the k- th double and so isIf “ a ” is an array of doubles, then a[ k ] is the k- th double and so is *(a + k). Adding a constant,, to a pointer actually adds to the value of the pointer.Adding a constant, k, to a pointer actually adds k * sizeof(pointer type) to the value of the pointer. This is one important reason why the type of a pointer must be specified when it’s defined.This is one important reason why the type of a pointer must be specified when it’s defined. We’ll see more on this later.We’ll see more on this later.

7/28/0910 ptrAdd.c int main() { char c, *cPtr = &c; int i, *iPtr = &i; double d, *dPtr = &d; printf("\nThe addresses of c, i and d are:\n"); printf("cPtr = %p, iPtr = %p, dPtr = %p\n", cPtr, iPtr, dPtr) ; cPtr = cPtr + 1 ; iPtr = iPtr + 1 ; dPtr = dPtr + 1 ; printf("\nThe values of cPtr, iPtr and dPtr are:\n") ; printf("cPtr = %p, iPtr = %p, dPtr = %p\n\n", cPtr, iPtr, dPtr) ; return 0; }

7/28/0911 Printing an Array The code below shows how to use an array name as a pointer void printStrings( char *strings[ ], int size ) { int i; for (i = 0; i < size; i++) printf( “%s\n”, *strings++); }

7/28/0912 Strings revisited Recall, in C, a string is represented as an array of characters terminated with a null (\0) character. As we’ve seen, arrays and pointers are closely related. A string constant may be declared as either a As we’ve seen, arrays and pointers are closely related. A string constant may be declared as either a char[ ] or char* char hello[ ] = “Hello Bobby”; or equivalently char *hi = “Hello Bob”; A could also be used to simplify coding; A typedef could also be used to simplify coding; typedef char* STRING; STRING hi = “Hello Bob”; In any case, the compiler will calculate the size of the char array required for the string (including the null) and the null terminator will automatically be appended to the end of the string, There are many library functions written to manipulate strings and characters. See appendix section B2 and B3 in K & R for a detailed list of function signatures and purpose.

7/28/0913 Arrays of Pointers Since pointers are variable, we can create an array of pointers just like we can create any array of any other type. Although the pointers may point to any type, the most common use of an array of pointers is an array of char* to create an array of strings.

7/28/0914 PointerArray.c int main( ) { int *pInt[3];/* an array of 3 "pointers to int */ int i, weight, height int *pAge = (int *)malloc( sizeof( int ) ); /* store some values */ weight = 185; height = 73; *pAge = 42; /* the pointers in the array can contain the address of local ** variables or malloc'd variables */ pInt[0] = pAge; pInt[1] = &height; pInt[2] = &weight; for (int i = 0; i < 3; i++) printf( "%d\n", *pInt[i]); return 0; }

7/28/0915 Boy’s Names A common use of an array of pointers is to create an array of strings. The declaration below creates an initialized array of strings (char *) for some boy’s names. The diagram below illustrates the memory configuration. char *name[] = { /* let the compiler computer the size */ “Bobby”, “Jim”, Harold” }; Bobby\0 Jim Harold names: 0 1 2

7/28/0916 Pointers2Pointer.c int main ( ) { /* a double, a pointer to double, ** and a pointer to a pointer to a double */ double gpa = 3.25, *pgpa, **ppgpa; /* make pgpa point to the gpa */ pgpa = &gpa; /* make ppgpa point to pgpa (which points to gpa) */ ppgpa = &pgpa; /* all of these print 3.25 */ printf( "%0.2f, %0.2f, %0.2f", gpa, *pgpa, **ppgpa); return 0; }

7/28/0917 char* array vs. char** Because the name of an array is a synonym for the address of the first element of the array, the name of the array may be treated like a pointer to the array. As a result, the name of an array of strings (for example) may be defined as either char *[ ] or char**. For example, the boy’s name array char *name[] = { “Bobby”, “Jim”, Harold” }; may also be defined as char **name = { “Bobby”, “Jim”, Harold” }; In particular, the parameters for main may be written as either int main (int argc, char *argv[ ])or int main( int argc, char **argv)

7/28/0918 Multidimensional Arrays C support multidimensional arrays using the standard [ ] indexing. The definition int a[5][4]; declares a rectangular, 2-d array with 5 rows, and 4 columns. Enough memory to hold 20 integers is allocated. An alternative definition is int *b[5];. This definition allocates enough memory for 5 int pointers for the rows. The pointers and the memory for the rows must be allocated an initialized. An advantage of this definition is that the rows need not be the same length. Brackets may still be used to access the elements.

7/28/0919 Command Line Arguments Command line arguments are passed to your program as parameters to main. int main( int argc, char *argv[ ] ) –argc is the number of command line arguments (and hence the size of argv ) –argv is an array of strings ( char *) which are the command line arguments. Note that argv[0] is always the name of your program. For example, typing myprog hello world 42 at the linux prompt results in –argc = 4 –argv[0] = “myprog” –argv[1] = “hello” –argv[2] = “world” –argv[3] = “42” Note that to use argv[3] as an integer, you must convert if from a string to an int using the library function atoi( ). E.g. int age = atoi( argv[3] );

7/28/0920 End of Class 5