Dynamic Allocation. Malloc - Reminder void* malloc(unsigned int nBytes); Used to dynamically allocate nBytes in memory Returns a pointer to the allocated.

Slides:



Advertisements
Similar presentations
Dynamic Allocation and Linked Lists. Dynamic memory allocation in C C uses the functions malloc() and free() to implement dynamic allocation. malloc is.
Advertisements

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.
Array_strcpy void array_strcpy(char dest[], char src[]) { int i = 0; while (src[i] != '\0') { dest[i] = src[i]; i++; } dest[i] = '\0'; }
Pointer, malloc and realloc 1. Name entered was 6 char, not enough space to put null terminator 2 Array of char.
ECE Application Programming Instructor: Dr. Michael Geiger Fall 2012 Lecture 31: Dynamic memory allocation.
CSE 251 Dr. Charles B. Owen Programming in C1 Dynamic Memory Allocation Dynamic memory allocation – How to allocate memory for variables (esp. arrays/strings)
Managing Memory Static and Dynamic Memory Type Casts Allocating Arrays of Dynamic Size Resizing Block of Memory Returning Memory from a Function Avoiding.
CSCI 171 Presentation 11 Pointers. Pointer Basics.
Managing Memory DCT 1063 PROGRAMMING 2 Mohd Nazri Bin Ibrahim Faculty of Computer, Media & Technology TATi University College
More Pointers Write a program that: –Calls a function to input an integer value –The above function calls another function that will double the input value.
ספטמבר 04Copyright Meir Kalech1 C programming Language Chapter 6: Dynamic Memory Allocation (DMA)
Programming C/C++ on Eclipe Trình bày : Ths HungNM C/C++ Training.
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.
CS61C L05 C Structures, Memory Management (1) Garcia, Spring 2005 © UCB Lecturer PSOE Dan Garcia inst.eecs.berkeley.edu/~cs61c.
Exercise 11 Dynamic allocation, structures, linked lists.
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.
11 Introduction to Programming in C - Fall 2010 – Erez Sharvit, Amir Menczel 1 Introduction to Programming in C תרגול
תכנות תרגול 6 שבוע : תרגיל שורש של מספר מחושב לפי הסדרה הבאה : root 0 = 1 root n = root n-1 + a / root n-1 2 כאשר האיבר ה n של הסדרה הוא קירוב.
Plab 2003 Exercise 4. Pointers to pointers. Plab 2003 Exercise 4 2 Pointers to pointers (1)int i=3 (2)int j=4; (3)int k=5; 3 i: 4 j: 5 k: ip1: ip2: (4)int.
1 More on Pointers. 2 Reminder 3 Pointers Pointer is a variable that contains the address of a variable Here P is said to point to the variable C C 7.
Exercise 11 Dynamic allocation and structures. Dynamic Allocation Array variables have fixed size, used to store a fixed and known amount of variables.
CS 61C L4 Structs (1) A Carle, Summer 2005 © UCB inst.eecs.berkeley.edu/~cs61c/su05 CS61C : Machine Structures Lecture #4: Strings & Structs
CSSE 332 Explicit Memory Allocation, Parameter passing, and GDB.
1 Structures, Dynamic Memory Allocation. 2 Agenda Structures Definition & usage Pointers to structures Arrays and pointers in structures Dynamic Memory.
C Slides and captured lecture (video and sound) are available at:
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
Programming Structures and Dynamic Allocation. Dynamic Memory Allocation The memory requirement of our program is not always known in advance  Arrays.
1 מבוא למדעי המחשב סיבוכיות. 2 סיבוכיות - מוטיבציה סידרת פיבונאצ'י: long fibonacci (int n) { if (n == 1 || n == 2) return 1; else return (fibonacci(n-1)
CS 61C L04 C Structures, Memory Management (1) Garcia, Fall 2004 © UCB Lecturer PSOE Dan Garcia inst.eecs.berkeley.edu/~cs61c.
Outline Midterm results Static variables Memory model
Introduction to Data Structures Systems Programming.
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.
C What you Know* Objective: To introduce some of the features of C. This assumes that you are familiar with C++ or java and concentrates on the features.
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.
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.
Introduction to Data Structures Systems Programming Concepts.
ECE Application Programming
Topics memory alignment and structures typedef for struct names bitwise & for viewing bits malloc and free (dynamic storage in C) new and delete (dynamic.
ECE Application Programming Instructors: Dr. Michael Geiger & Nasibeh Nasiri Fall 2015 Lecture 31: Structures (cont.) Dynamic memory allocation.
Advanced Pointer Topics. Pointers to Pointers u A pointer variable is a variable that takes some memory address as its value. Therefore, you can have.
1 Pointers: Parameter Passing and Return. 2 Passing Pointers to a Function Pointers are often passed to a function as arguments  Allows data items within.
C Primer Session – 1/25/01 Outline Hello World Command Line Arguments Bit-wise Operators Dynamic Memory / Pointers Function Parameters Structures.
MORE POINTERS Plus: Memory Allocation Heap versus Stack.
More Pointers in C Computer Organization I 1 August 2009 © McQuain, Feng & Ribbens Allocating Arrays Dynamically You allocate an array by.
Announcements Partial Credit Due Date for Assignment 2 now due on Sat, Feb 27 I always seem to be behind and get tons of daily. If you me and.
DYNAMIC MEMORY ALLOCATION. Disadvantages of ARRAYS MEMORY ALLOCATION OF ARRAY IS STATIC: Less resource utilization. For example: If the maximum elements.
Dynamic Allocation in C
Programming Arrays.
Pointers & Arrays 1-d arrays & pointers 2-d arrays & pointers.
2016.
Pointers Department of Computer Science-BGU יום שלישי 31 יולי 2018.
Programming Languages and Paradigms
Arrays & Dynamic Memory Allocation
CS157: Dynamic Memory Dynamic Memory 11/9/201804/25/06.
קורס תכנות שיעור 13: רשימות מקושרות.
Pointers Department of Computer Science-BGU יום רביעי 21 נובמבר 2018.
Programming Linked Lists.
CSC215 Lecture Memory Management.
Dynamic Memory Allocation
- Dynamic Allocation - Linked lists
EECE.2160 ECE Application Programming
C What you Know* Objective: To introduce some of the features of C. This assumes that you are familiar with C++ or java and concentrates on the features.
Dynamic Allocation in C
EECE.2160 ECE Application Programming
EECE.2160 ECE Application Programming
Dynamic Memory – A Review
EECE.2160 ECE Application Programming
Presentation transcript:

Dynamic Allocation

Malloc - Reminder void* malloc(unsigned int nBytes); Used to dynamically allocate nBytes in memory Returns a pointer to the allocated area on success, NULL on failure Always check whether memory was successfully allocated

The free Function void free(void *ptr); free(p) deallocates memory pointed by p. Freeing a non-allocated area is an error. No partial deallocation. Always free allocated memory.

Warming Up int main() { int i=0, n=0, *p=NULL; printf("How many numbers will you enter?\n"); scanf("%d", &n); /* Allocate an int array of the proper size */ p = (int*)malloc(n * sizeof(int)); if (p == NULL) { printf("Memory allocation failed!\n"); return 1; }... /* Free the allocated space */ free(p); return 0; } casting

Returning Allocated Memory Example: duplicate a string to a new location (with dynamic allocation), return the new string: // strdup - duplicate a string char* strdup(const char* str) { char* dup = (char*)malloc((strlen(str)+1) * sizeof(char)); if (dup != NULL) { strcpy(dup, str); } return dup; }

Exercise Implement the function char* my_strcat(const char *s1, const char *s2); Output: a pointer to a dynamically allocated concatenation of s1 and s2. Example: my_strcat(“hello_”, “world!”); Output: “hello_world!” You can use the functions in string.h Test your function

What’s Wrong Here? char* my_strcat(const char *s1, const char *s2) { char result[500]; /* assume this is enough */ strcpy(result, s1); strcpy(result + strlen(s1), s2); return result; }

Pitfalls Accessing un-initialized pointer int* p; *p = 3; Using de-allocated memory int* p = (int*)malloc(SIZE * sizeof(int));... /* do something with p*/ free(p); *p = 0;

Dynamic Array Imagine that you own a rapidly growing business that currently has 50 customers Every customer has a struct containing her details: typedef struct { char name[MAX_LEN]; … } Customer;

Dynamic Array The pool is kept in an array of customers: Customer customers_arr[SIZE]; But What is SIZE? #define SIZE 50 ? Not enough #define SIZE ? What a waste

Dynamic Array Solution: current size ~ 50, grow on demand. Take 1: On insertion - if the array is full re-allocate space for n+1 elements Problem: copying n elements per insertion is expensive.

Dynamic Array Take 2: if the array is full: Re-allocate space for 2n elements.

Dynamic Array - Code typedef struct { Customer * arr; int len; int capacity; } Darray; Darray init_array(int capacity) { Darray darr; darr.arr = (Customer *)malloc(capacity *sizeof(Customer)); if (darr.arr == NULL) { printf("Memory allocation failed\n"); exit(1); } darr. capacity = capacity; darr.len = 0; return darr; }

Dynamic Array - Code void insert(Darray * darr, Customer * customer) { if (darr->len == darr->capacity) { darr->arr = (Customer *)realloc(darr->arr, darr->capacity*2*sizeof(Customer)); if (darr->arr == NULL) { printf("Memory allocation failed\n"); exit(1); } darr->capacity *= 2; } darr->arr[darr->len] = *customer; darr->len++; }

Dynamic Array - Code int main() { Darray dynamic_array = init_array(ARR_INIT_SIZE); int i; Customer customer; // insert customers for (i = 0; i < 10; ++i) { printf("insert customer %d:\n", i+1); readString(customer.name, STRING_MAX_SIZE); insert(&dynamic_array, customer); } // print array for (i = 0; i < 10; ++i) printf("Customer %d: %s\n", i+1, dynamic_array.arr[i].name); free(dynamic_array.arr); return 0; }

Dynamic String Conventionally, we represent a string as a char array that marks the end of the string with the special char ‘\0’. \0

Dynamic String - Definition We will now consider a different representation : typedef struct { char *data; int capacity, length; } string; data points to a dynamically allocated char array. capacity is length of the char array len is length of the actual string capacity len H e l l o data

Dynamic String Pro: The string’s length can dynamically change Safe code – we can easily check that the array is long enough when expanding the string No need to pass the array length separately Cons: Functions defined in string.h won’t work

Dynamic String - Allocation Initialize: string *allocateString() { string *result = (string*) malloc(sizeof(string)); if (result != NULL) { result->data = NULL; result->capacity = 0; result->length = 0; } return result; } Ensure allocation

Dynamic String – Ensure Capacity Re-allocate on demand void ensureCapacity(string *str, int minCapacity) { if (str->capacity >= minCapacity) return; str->data = (char*) realloc(str->data, minCapacity); if (str->data == NULL) { printf("Fatal error: memeory allocation failed!\n"); exit(1); } str->capacity = minCapacity; } Ensure re-allocation

Dynamic String – Free String “Deep” free: void freeString(string *str) { if (str != NULL) { if (str->data != NULL) free(str->data); free(str); }

Dynamic String - Concatenate Concatenate dest + source into dest string* append(string *dest, const string *source) { ensureCapacity(dest, dest->length + source->length); memcpy(dest ->data + dest->length, source->data, source->length); dest->length += source->length; return dest; } something thing + = some destsource dest memcpy instead of strcpy

Dynamic String – Convert Are both representations equivalent? Can we convert any C string (null-terminated) to the new string struct? - Yes, easily (see next slide). What about converting a string struct to a C string?

Dynamic String – Convert string * convertCString(const char *cstr) { string *result = NULL; int cstrlen = 0; result = allocateString(); if (result != NULL) { cstrlen = strlen(cstr); ensureCapacity(result, cstrlen); memcpy(result->data, cstr, cstrlen); result->length = cstrlen; { return result; }

שאלה ממבחן - תש"ע, סמסטר א',שאלה 2 בשאלה זו תתבקשו לכתוב פונקציות ותוכנת מחשב לניהול משחק הלוטו. סעיף א': "מערך משורשר" - מערך המכיל ערכים של מספר תתי מערכים באותו אורך באופן רציף בזה אחר זה. לדוגמא, "מערך משורשר" המכיל 3 תתי מערכים, כל אחד בגודל 6:

שאלה ממבחן - תש"ע, סמסטר א',שאלה 2 כתבו פונקציה המקבלת: - מערך של מספרים שלמים שהוא "מערך משורשר" - גודל כל תת- מערך n. - 2 מספרים שלמים, i ו-j. הפונקציה תחזיר את arr[i][j]. int getVal(int arr[], int n, int i, int j) { return arr[i * n + j]; }

שאלה ממבחן - תש"ע, סמסטר א',שאלה 2 סעיף ב: מגרילים 6 מספרים בין 1 ל-49. טופס מנצח מכיל את כל 6 המספרים. ממשו פונקציה הבודקת מי הם הזוכים, המקבלת: winNums - מערך בגודל 6 המכיל את המספרים הזוכים. Tickets - מערך משורשר עם תתי מערכים באורך 6 ובהם טפסים של משתתפים. numTickets - מספר הטפסים במערך. res - מערך בגודל מספר המשתתפים. בסיום הריצה, התא ה-i ב- resיכיל 1 אם הטופס ה-i זכה בפרס ו-0 אחרת. ערך מוחזר: מספר הטפסים הזוכים.

שאלה ממבחן - תש"ע, סמסטר א',שאלה 2 כדי לקבל את מלוא הנקודות בסעיף זה יש לעבור רק פעם אחת על המערך winNums ורק פעם אחת על המערך tickets. ניצור מערך עזר בגודל 49 שיבדוק אם מספר הוא מספר זוכה באמצעות פעולת השוואה אחת בלבד!

שאלה ממבחן - תש"ע, סמסטר א',שאלה 2 #define TICKET_SIZE 6 #define NUM_RANGE 49 int checkWin(int winNums[], int tickets[], int numTickets, int res[]) { int i, j, val, numWinners = 0; char numbers[NUM_RANGE]={0}; // init auxiliary array for (i = 0; i < TICKET_SIZE; i++) numbers[winNums[i]] = 1; Auxiliary array

שאלה ממבחן - תש"ע, סמסטר א',שאלה 2 // go over all tickets for (i = 0; i < numTickets; i++) { res[i] = 1; // go over 6 numbers in a ticket for (j = 0; j < TICKET_SIZE; j++) { val = getVal(tickets, TICKET_SIZE, i, j); if (numbers[val] == 0) { // found a non-winning number – ticket lost res[i] = 0; break; } { // if we are here – all 6 numbers won numWinners += res[i]; } return numWinners; }

שאלה ממבחן - תש"ע, סמסטר א',שאלה 2 סעיף ג' ( 15 נקודות) : הפרס הראשון בלוטו הוא 10,000,000 ש"ח. אם כמה משתתפים זכו הם יתחלקו בפרס באופן שווה (ייתכן שאין זוכה). כתבו תוכנית הקולטת מהמשתמש את הנתונים הבאים לפי הסדר המתואר: 1. ששת המספרים הזוכים 2. מספר המשתתפים 3. טפסי הניחוש בזה אחר זה פלט התוכנית הוא טבלה שבכל שורה בה מופיע מספר סידורי של משתתף וסכום הזכייה שלו.

שאלה ממבחן - תש"ע, סמסטר א',שאלה 2 int main() { int i, numParticipants, numWinners = 0; int winningNumbers[TICKET_SIZE]; int *tickets, *winners; double jackpot = ; printf("Enter winning numbers: "); for (i = 0; i < TICKET_SIZE; i++) scanf("%d", &winningNumbers[i]); printf("Enter number of participants: "); scanf("%d", &numParticipants); // dynamic allocation tickets = (int*) malloc(numParticipants *TICKET_SIZE * sizeof(int)); winners = (int*) malloc(numParticipants *sizeof(int));

שאלה ממבחן - תש"ע, סמסטר א',שאלה 2 if (tickets == NULL || winners == NULL) { printf("Unable to allocate memory!"); return 1; } printf("Enter lottery tickets: "); … numWinners = checkWin(winningNumbers, tickets,numParticipants, winners);... // free allocated memory free(tickets); free(winners); return 0; {

Solution to Class exercise char* my_strcat(const char *s1, const char *s2) { int len; char *result = NULL; len = strlen(s1) + strlen(s2) + 1; result = (char*)malloc(len * sizeof(char)); if (result == NULL) { printf(“Memory allocation failed!\n"); return NULL; } strcpy(result, s1); strcat(result, s2); return result; }