Introduction to C. Memory Model. Instructor: Yin Lou 02/04/2011. Introduction to C CS 2022, Spring 2011, Lecture 6

Similar documents
Memory management. Announcements. Safe user input. Function pointers. Uses of function pointers. Function pointer example

Lecture 11 Doubly Linked Lists & Array of Linked Lists. Doubly Linked Lists

The C Programming Language course syllabus associate level

Lecture 10: Dynamic Memory Allocation 1: Into the jaws of malloc()

Object Oriented Software Design II

Leak Check Version 2.1 for Linux TM

Chapter 5 Names, Bindings, Type Checking, and Scopes

Sources: On the Web: Slides will be available on:

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas

Restraining Execution Environments

6.088 Intro to C/C++ Day 4: Object-oriented programming in C++ Eunsuk Kang and Jean Yang

Stacks. Linear data structures

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C

C Interview Questions

1 Abstract Data Types Information Hiding

Scoping (Readings 7.1,7.4,7.6) Parameter passing methods (7.5) Building symbol tables (7.6)

An Implementation of a Tool to Detect Vulnerabilities in Coding C and C++

Semantic Analysis: Types and Type Checking

Parameter passing in LISP

Coding Rules. Encoding the type of a function into the name (so-called Hungarian notation) is forbidden - it only confuses the programmer.

Lecture Data Types and Types of a Language

COMP 356 Programming Language Structures Notes for Chapter 10 of Concepts of Programming Languages Implementing Subprograms.

arrays C Programming Language - Arrays

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

Java Interview Questions and Answers

1) The postfix expression for the infix expression A+B*(C+D)/F+D*E is ABCD+*F/DE*++

ECS 165B: Database System Implementa6on Lecture 2

Short Notes on Dynamic Memory Allocation, Pointer and Data Structure

C# and Other Languages

C Dynamic Data Structures. University of Texas at Austin CS310H - Computer Organization Spring 2010 Don Fussell

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

Virtual Servers. Virtual machines. Virtualization. Design of IBM s VM. Virtual machine systems can give everyone the OS (and hardware) that they want.

Embedded Programming in C/C++: Lesson-1: Programming Elements and Programming in C

C Compiler Targeting the Java Virtual Machine

JVM Tool Interface. Michal Pokorný

KITES TECHNOLOGY COURSE MODULE (C, C++, DS)

Boolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority)

Debugging. Common Semantic Errors ESE112. Java Library. It is highly unlikely that you will write code that will work on the first go

Keil C51 Cross Compiler

CS412/CS413. Introduction to Compilers Tim Teitelbaum. Lecture 20: Stack Frames 7 March 08

Object Oriented Software Design II

Habanero Extreme Scale Software Research Project

Lecture 22: C Programming 4 Embedded Systems

Bypassing Browser Memory Protections in Windows Vista

How to create/avoid memory leak in Java and.net? Venkat Subramaniam

Parameter Passing. Parameter Passing. Parameter Passing Modes in Fortran. Parameter Passing Modes in C

Contents. 9-1 Copyright (c) N. Afshartous

A C Test: The 0x10 Best Questions for Would-be Embedded Programmers

Parameter Passing. Standard mechanisms. Call by value-result Call by name, result

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

5 Arrays and Pointers

Stack machines The MIPS assembly language A simple source language Stack-machine implementation of the simple language Readings:

Memory Allocation. Static Allocation. Dynamic Allocation. Memory Management. Dynamic Allocation. Dynamic Storage Allocation

Lecture 32: The Java Virtual Machine. The Java Virtual Machine

Programming Embedded Systems

Crash Course in Java

No no-argument constructor. No default constructor found

1 The Java Virtual Machine

Organization of Programming Languages CS320/520N. Lecture 05. Razvan C. Bunescu School of Electrical Engineering and Computer Science

Java from a C perspective. Plan

Software Vulnerabilities

Stack Allocation. Run-Time Data Structures. Static Structures

Compiling Object Oriented Languages. What is an Object-Oriented Programming Language? Implementation: Dynamic Binding

PROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON

Moving from CS 61A Scheme to CS 61B Java

CMSC 202H. ArrayList, Multidimensional Arrays

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

CS 106 Introduction to Computer Science I

Lecture 5: Java Fundamentals III

Interpreters and virtual machines. Interpreters. Interpreters. Why interpreters? Tree-based interpreters. Text-based interpreters

Operator Overloading. Lecture 8. Operator Overloading. Running Example: Complex Numbers. Syntax. What can be overloaded. Syntax -- First Example

Cyclone: A Type-Safe Dialect of C

Java Basics: Data Types, Variables, and Loops

Building Embedded Systems

An Incomplete C++ Primer. University of Wyoming MA 5310

El Dorado Union High School District Educational Services

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

How To Understand How A Process Works In Unix (Shell) (Shell Shell) (Program) (Unix) (For A Non-Program) And (Shell).Orgode) (Powerpoint) (Permanent) (Processes

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

Java CPD (I) Frans Coenen Department of Computer Science

Cataloguing and Avoiding the Buffer Overflow Attacks in Network Operating Systems

C++ INTERVIEW QUESTIONS

Operating Systems and Networks

Java Programming. Binnur Kurt Istanbul Technical University Computer Engineering Department. Java Programming. Version 0.0.

DATA STRUCTURE - STACK

Persistent Binary Search Trees

Linked Lists Linked Lists, Queues, and Stacks

Software Engineering Concepts: Testing. Pointers & Dynamic Allocation. CS 311 Data Structures and Algorithms Lecture Slides Monday, September 14, 2009

Lecture 11: Tail Recursion; Continuations

Týr: a dependent type system for spatial memory safety in LLVM

Threads Scheduling on Linux Operating Systems

Advanced compiler construction. General course information. Teacher & assistant. Course goals. Evaluation. Grading scheme. Michel Schinz

Transcription:

Introduction to C Memory Model Instructor: Yin Lou 02/04/2011

Recap: Pointers int *ptr; Pointers are variables that store memory address of other variables Type of variable pointed to depends on type of pointer:

Recap: Pointers int *ptr; Pointers are variables that store memory address of other variables Type of variable pointed to depends on type of pointer: int *ptr points to an integer value char *ptr points to character variable

Recap: Pointers int *ptr; Pointers are variables that store memory address of other variables Type of variable pointed to depends on type of pointer: int *ptr points to an integer value char *ptr points to character variable Can cast between pointer types: myintptr = (int *) myotherptr;

Recap: Pointers int *ptr; Pointers are variables that store memory address of other variables Type of variable pointed to depends on type of pointer: int *ptr points to an integer value char *ptr points to character variable Can cast between pointer types: myintptr = (int *) myotherptr; void *ptr has an unspecified type (generic pointer); must be cast to a type before used

Recap: Pointers Two main operations * dereference: get the value at the memory location stored in a pointer & address of: get the address of a variable int *myptr = &myvar; Pointer arithmetic: directly manipulate a pointer s content to access other locations Use with caution!: can access bad areas of memory and cause a crash However, it is useful in accessing and manipulating data structures Can have pointers to pointers int **my2darray;

Memory Program code Function variables Arguments Local variables Return location Global Variables Statically allocated Dynamically allocated

The Stack Stores Function local variables Temporary variables Arguments for next function call Where to return when function ends

The Stack Managed by compiler One stack frame each time function called Created when function called Stacked on top (under) one another Destroyed at function exit

What Can Go Wrong? char *my_strcat(char *s1, char *s2) { char s3[1024]; strcpy(s3, s1); strcat(s3, s2); return s3; }

What Can Go Wrong? char *my_strcat(char *s1, char *s2) { char s3[1024]; strcpy(s3, s1); strcat(s3, s2); return s3; } Recall that local variables are stored on the stack Memory for local variables is deallocated when function returns Returning a pointer to a local variable is almost always a bug!

What Can Go Wrong? Run out of stack space Unintentionally change values on the stack In some other function s frame Even return address from function Access memory even after frame is deallocated

The Heap C can use space in another part of memory: the heap

The Heap C can use space in another part of memory: the heap The heap is separate from the execution stack Heap regions are not deallocated when a function returns Note: this is completely unrelated to the Heap data structure

The Heap C can use space in another part of memory: the heap The heap is separate from the execution stack Heap regions are not deallocated when a function returns Note: this is completely unrelated to the Heap data structure The programmer requests storage space on the heap C never puts variables on the heap automatically But local variables might point to locations on the heap Heap space must be explicitly allocated and deallocated by the programmer

malloc Library function in stdlib.h Stands for memory allocate

malloc Library function in stdlib.h Stands for memory allocate Requests a memory region of a specified size Syntax: void *malloc(int size) void * is generic pointer type

Usage int main() { int *p = (int *) malloc(10 * sizeof(int)); if (p == NULL) { // do cleanup } // do something free(p); return 0; }

Usage int main() { int *p = (int *) malloc(10 * sizeof(int)); if (p == NULL) { // do cleanup } // do something free(p); return 0; } MUST check the return value from malloc MUST explicitly free memory when no longer in use

What Can Go Wrong? Run out of heap space: malloc returns 0 Unintentionally change other heap data Access memory after free d free memory twice

Usage int main() { int *p = (int *) malloc(10 * sizeof(int)); if (p == NULL) { // do cleanup } // do something if (p!= NULL) { free(p); p = NULL; } return 0; }

Garbage Collection in C Pointers make garbage collection difficult or impossible Its very difficult to determine whether memory is still being used Javas references are a restricted form of pointers that don t allow arithmetic, just because of this issue There are garbage collecting libraries for C, but they aren t guaranteed to work with any program

Garbage Collection in C Pointers make garbage collection difficult or impossible Its very difficult to determine whether memory is still being used Javas references are a restricted form of pointers that don t allow arithmetic, just because of this issue There are garbage collecting libraries for C, but they aren t guaranteed to work with any program Example char *s = (char *) malloc(1024); s -= 10000; // nothing points to the allocated memory // region. Could it be garbage collected? s += 10000; // no, because now something points to it again!

Multidimensional Arrays On the stack: int a[10][20]; Initialization: int a[][] = {{1, 2, 3}, {4, 5, 6}}; Accessing the array: a[1][0]

Multidimensional Arrays On the stack: int a[10][20]; Initialization: int a[][] = {{1, 2, 3}, {4, 5, 6}}; Accessing the array: a[1][0] On the heap int **a = (int **) malloc(10 * sizeof(int *)); for (int i = 0; i < 10; ++i) { a[i] = (int *) malloc(20 * sizeof(int)); } Don t forget to free them!