CSE2301. Dynamic memory Allocation. malloc() Dynamic Memory Allocation and Structs

Similar documents
Arrays and Pointers (part 1)

Arrays and Pointers. CSE 2031 Fall November 11, 2013

Arrays and Pointers (part 1)

Arrays and Pointers. Arrays. Arrays: Example. Arrays: Definition and Access. Arrays Stored in Memory. Initialization. EECS 2031 Fall 2014.

Pointers (part 1) What are pointers? EECS We have seen pointers before. scanf( %f, &inches );! 25 September 2017

Dynamic memory allocation (malloc)

Dynamic Memory Allocation

Lecture 8 Dynamic Memory Allocation

advanced data types (2) typedef. today advanced data types (3) enum. mon 23 sep 2002 defining your own types using typedef

C PROGRAMMING Lecture 5. 1st semester

Subject: Fundamental of Computer Programming 2068

Unit IV & V Previous Papers 1 mark Answers

In Java we have the keyword null, which is the value of an uninitialized reference type

Chapter 2 (Dynamic variable (i.e. pointer), Static variable)

COP 3223 Introduction to Programming with C - Study Union - Fall 2017

C Pointers. Abdelghani Bellaachia, CSCI 1121 Page: 1

Arrays and Pointers (part 2) Be extra careful with pointers!

int marks[10]; // fixed size and fixed address No change in Memory address.

Quick review pointer basics (KR ch )

Content. In this chapter, you will learn:

Binghamton University. CS-211 Fall Dynamic Memory

Computer Systems and Networks

Memory Allocation in C C Programming and Software Tools. N.C. State Department of Computer Science

IV Unit Second Part STRUCTURES

Actually, C provides another type of variable which allows us to do just that. These are called dynamic variables.

Memory Management. CSC215 Lecture

Dynamic Allocation of Memory

Structures. Basics of Structures (6.1) EECS l Now struct point is a valid type. l Defining struct variables: struct point { int x; int y; };

Language comparison. C has pointers. Java has references. C++ has pointers and references

Programming. Pointers, Multi-dimensional Arrays and Memory Management

Arrays and Pointers (part 2) Be extra careful with pointers!

BLM2031 Structured Programming. Zeyneb KURT

CSCI 171 Chapter Outlines

C Programming SYLLABUS COVERAGE SYLLABUS IN DETAILS

Dynamic memory allocation

Arrays, Pointers and Memory Management

CSE2301. Arrays. Arrays. Arrays and Pointers

Self-referential Structures and Linked List. Programming and Data Structure 1

CS 33. Intro to Storage Allocation. CS33 Intro to Computer Systems XXVI 1 Copyright 2017 Thomas W. Doeppner. All rights reserved.

Linked-List Basic Examples. A linked-list is Linear collection of self-referential class objects, called nodes Connected by pointer links

Outline. Briefly review the last class Pointers and Structs Memory allocation Linked lists

Linked List in Data Structure. By Prof. B J Gorad, BECSE, M.Tech CST, PHD(CSE)* Assistant Professor, CSE, SITCOE, Ichalkaranji,Kolhapur, Maharashtra

Memory Allocation. General Questions

ELEC / COMP 177 Fall Some slides from Kurose and Ross, Computer Networking, 5 th Edition

6.S096: Introduction to C/C++

C Structures & Dynamic Memory Management

Quick review of previous lecture Ch6 Structure Ch7 I/O. EECS2031 Software Tools. C - Structures, Unions, Enums & Typedef (K&R Ch.

IMPORTANT QUESTIONS IN C FOR THE INTERVIEW

COP 3223 Introduction to Programming with C - Study Union - Spring 2018

Chapter 14. Dynamic Data Structures. Instructor: Öğr. Gör. Okan Vardarlı. Copyright 2004 Pearson Addison-Wesley. All rights reserved.

Computer Programming Unit 3

19-Nov CSCI 2132 Software Development Lecture 29: Linked Lists. Faculty of Computer Science, Dalhousie University Heap (Free Store)

This code has a bug that allows a hacker to take control of its execution and run evilfunc().

Memory Management. CS449 Fall 2017

Announcements. assign0 due tonight. Labs start this week. No late submissions. Very helpful for assign1

o Code, executable, and process o Main memory vs. virtual memory

AMCAT Automata Coding Sample Questions And Answers

COP 3223 Introduction to Programming with C - Study Union - Fall 2017

APS105. Malloc and 2D Arrays. Textbook Chapters 6.4, Datatype Size

Hacking in C. Memory layout. Radboud University, Nijmegen, The Netherlands. Spring 2018

CA341 - Comparative Programming Languages

CS 11 C track: lecture 5

Memory (Stack and Heap)

CS349/SE382 A1 C Programming Tutorial

CS 137 Part 5. Pointers, Arrays, Malloc, Variable Sized Arrays, Vectors. October 25th, 2017

Pointers. Part VI. 1) Introduction. 2) Declaring Pointer Variables. 3) Using Pointers. 4) Pointer Arithmetic. 5) Pointers and Arrays

14. Memory API. Operating System: Three Easy Pieces

A Fast Review of C Essentials Part I

Variation of Pointers

Procedural programming with C

The C Programming Language Part 4. (with material from Dr. Bin Ren, William & Mary Computer Science, and

Pointers. Introduction

Character Strings. String-copy Example

C BOOTCAMP DAY 2. CS3600, Northeastern University. Alan Mislove. Slides adapted from Anandha Gopalan s CS132 course at Univ.

Dynamic memory. EECS 211 Winter 2019

C Programming Language: C ADTs, 2d Dynamic Allocation. Math 230 Assembly Language Programming (Computer Organization) Thursday Jan 31, 2008

A3-R3: PROGRAMMING AND PROBLEM SOLVING THROUGH 'C' LANGUAGE

Programs in memory. The layout of memory is roughly:

Class Information ANNOUCEMENTS

CSCI-243 Exam 1 Review February 22, 2015 Presented by the RIT Computer Science Community

Fundamental of Programming (C)

EM108 Software Development for Engineers

M1-R4: Programing and Problem Solving using C (JAN 2019)

Memory Allocation in C

dynamic memory allocation

These problems are provided to you as a guide for practice. The questions cover important concepts covered in class.

4) In C, if you pass an array as an argument to a function, what actually gets passed?

Structures and Pointers

Dynamic Data Structures. CSCI 112: Programming in C

POINTER AND ARRAY SUNU WIBIRAMA

Dynamic Memory Allocation (and Multi-Dimensional Arrays)

CSE2301. Introduction

Kurt Schmidt. October 30, 2018

2/28/2018. Overview. The C Programming Language Part 4. Pointers. Pointers. Pointers. Pointers

Lecture07: Strings, Variable Scope, Memory Model 4/8/2013

C Tutorial. Pointers, Dynamic Memory allocation, Valgrind, Makefile - Abhishek Yeluri and Yashwant Reddy Virupaksha

C Programming Language

MODULE 5: Pointers, Preprocessor Directives and Data Structures

Variables Data types Variable I/O. C introduction. Variables. Variables 1 / 14

Dynamic Memory Allocation and Linked Lists

Transcription:

Warning: These notes are not complete, it is a Skelton that will be modified/add-to in the class. If you want to us them for studying, either attend the class or get the completed notes from someone who did CSE2301 Dynamic Memory Allocation and Structs These slides are based on slides by Prof. Wolfgang Stuerzlinger at York University Dynamic memory Allocation How to allocate memory during run time. int x=10; int myarray[x]; That is not allowed in ANSI C malloc() In stdlib.h void *malloc(int n); Allocate memory at run time. Returns a pointer (to a void) to at least n bytes available. Returns null if the memory was not allocated. The memory are not initialized. 1

calloc() void *calloc(int n, int s); Allocates an array of n elements where each element has size s; calloc initializes memory to 0. realloc() What if we want our array to grow (or shrink)? void * realloc(void *ptr, int n); Resizes a previously allocated block of memory. ptr must have been returned from either calloc, malloc, or realloc. Array me be moved if it could not be extended in its current location. free() void free(void *ptr) Releases the memory we previously allocated. ptr must have been returned by malloc, alloc, or realloc. 2

#include<stdio.h> #include<stdlib.h> main() { int *a, i,n,sum=0; printf( Input an aray size ); scanf( %d,&n); a=calloc(n, sizeof(int)); } for(i=0; i<n; i++) scanf( %d,&a[i]); for(i=0; i<n; i++) sum+=a[i]; free(a); printf( Number of elelments = %d and the sum is %d\n,n,sum); Trouble with Pointers Overruns and underruns Occurs when you reference a memory beyond what you allocated. Uninitiaized pointers int *x; *x=20; Trouble with Pointers Uninitialized pointers main() { char *x[10]; strcpy(x[1], Hello ); } 3

Trouble with Pointers Null-Pointers De-referencing main() { int *x; int size; x=(int*) malloc(size); *x = 20; // What is wrong } Trouble with Pointers A better way of doing it x=(int *) malloc(size); if(x == NULL) { printf( ERROR \n ); exit(1); } *x=20; Memory Leaks int *x; x=(int *) malloc(20); x=(int *) malloc(30); The first memory block is lost for ever. MAY cause problems (memory leak). 4

Trouble with Pointers Inappropriately use freed memory char *x; x=(char *) malloc(50); free(x); x[0]= A ; Does work on my system Trouble with Pointers Inappropriately freed memory char *x=null; free(x); x=malloc(50); free(x+1); free(x) free(x) Structures struct { float width; float height; } chair, table; chair and table are variables struct { } is the type 5

Structures Accessing the members is done via. Operator chair.width=10; table.height= chair.width+20; Struct s assignment is a shallow copy chair = table; &chair is the address of the variable chair of type struct {.} Structures struct dimension { float width; int height; }; Now, struct dimension is a valid type struct dimension a,chair,table; Structures Struct names have their own namespace separate from variables and functions; Struct member names have their own namespace. struct dimension dimension; struct dimesnsion { float width; float height; } height; 6

struct Part { int number; float x,y,z; }; To define a variable struct Part p1, p2; typedef struct { int number; float x,y,z; } Part; To define a variable Part p1,p2; Structures You can pass structure as arguments fo functions float get_area(struct dimension d) { return d.width * d.height; } This is a call-by-value, a copy of the structure is sent to the function Structures Structure can returned from functions. struct dimension make_dim(int width, int height) { struct dimension d; d.width = width; d.height = height; return d; } 7

Structure Pointers struct dimension table, *p; p= &table; *p.width (*p).width; You can use p->width; WRONG,. has a higher precedence Structures It is inefficient to pass large structures to functions, instead use pointers and you can manipulate the same structure. Example #include <stdio.h> main() { 111 11 struct { 222 12 int len; int height; } tmp, *p=&tmp; tmp.len=10; tmp.height=20; printf(" 111 %d \n",++(p->len)); printf(" 222 %d \n",++p->len); } 8

Linked List struct list { int data; struct list *next; }; It is O.K. to use a pointer to a struct that is declared but not defined 3 Linked List Pointer head points to the first element Last element pointer is NULL head 3 3 3 NULL Linked List #include <stdio.h> #include <stdlib.h> main() { struct list{ int len; struct list *next; } *head,*p,*last; head=(struct list *)malloc(sizeof(list)); head->len=1; head->next=null; last=head; int i; scanf("%d",&i); } while(i>=0) { scanf("%d",&i); p = (struct list *)malloc(sizeof(list)); p->len=i; p->next=null; last->next=p; last=p; } printf("enter the number you want to search for "); scanf("%d",&i); for(p=head; p!=null; p=p->next) if(p->len == i) printf("found \n"); 9

Delete a node void deleteit(dim **p, int i) { // DOES NOT WORK 1 st element dim **p1,*temp; p1=p; while((*p1)->num!= i) p1=&(*p1)->next; temp = *p1; *p1 = (*p1)->next; free(temp); } p is a pointer to head (pointer to 1 st element in list Debug it Array of Structures struct dimension { float width; float height; }; struct dimension chairs[2]; struct dimension *tables; tables = (struct dimension*) malloc (20*sizeoff(struct dimension)); Initializing Structures struct dimension sofa={2.0, 3.0}; struct dimension chairs[] = { {1.4, 2.0}, {0.3, 1.0}, {2.3, 2.0} }; 10

Nested Structures struct point {int x, int y;}; struct line { struct point a; struct point b; } myline; myline.a.x=0; myline.a.y=5; Structs struct {float w,h;} chair; struct dim {float w,h;} chair1; struct dim {float w,h;}; struct dim chair2; typedef struct {float w,h;} dim; dim x,y; typedef We can define a new type and use it later typedef struct { int x,y; float z; } newtype; newtype a1,b1,c1,x; Now, newtype is a type in C just like int and float 11

Unions union value { int I; char c; float f; }; Similar to struct but all variables share the same memory location, we access them differently unin value v; v.f=2.3; v.i=45;. Enumeration enum state { IN, OFF, }x; x=in; if (x==off) { }; Values starts at zero unless otherwise specified Enumeration enum my_var { RED = 1, BLUE, /* by definition 2 */ GREEN = 16, YELLOW, /* 17 */ }; 12