Lecture 3 Memory and Pointers

Size: px
Start display at page:

Download "Lecture 3 Memory and Pointers"

Transcription

1 Lecture 3 Memory and Pointers

2 Lets think about memory We can think of memory as a series of empty slots Each cell in the slot will hold 1 Byte To identify which cell something is in we need an identifier. This is called a memory address This is allocated by the OS when we communicate with it that we need a memory slot

3 Remember this? sizeof( data type) sizeof(char)= 1 sizeof(short int)= 2 sizeof(int)= 4 sizeof(long int)= 8 unsigned versions sizeof(unsigned char)= 1 sizeof(unsigned short int)= 2 sizeof(unsigned int)= 4 sizeof(unsigned long int)= 8 this tells us how many 1 byte memory cells each data type uses

4 #include <stdio.h> #include <stdlib.h> int main() { printf("sizeof(char)= %ld \n",sizeof(char)); printf("sizeof(short int)= %ld \n",sizeof(short int)); printf("sizeof(int)= %ld \n",sizeof(int)); printf("sizeof(long int)= %ld \n",sizeof(long int)); printf("unsigned versions\n"); printf("sizeof(unsigned char)= %ld \n",sizeof(unsigned char)); printf("sizeof(unsigned short int)= %ld \n",sizeof(unsigned short int)); printf("sizeof(unsigned int)= %ld \n",sizeof(unsigned int)); printf("sizeof(unsigned long int)= %ld \n",sizeof(unsigned long int)); } return EXIT_SUCCESS; sizeof(char)=1 Memory Cell Block sizeof(short int)=2 sizeof(int)=4 sizeof(long int)=8 sizeof(float)=4 sizeof(double)=8

5 & the address operator Sometimes know as a reference operator will give us the memory address of the cell containing the value we can usually use & to print it out. #include <stdio.h> #include <stdlib.h> int main() { int i=0; char c='c'; double d=1.0; float f=1.0; printf("i address is %p \n",&i); printf("c address is %p \n",&c); printf("d address is %p \n",&d); printf("f address is %p \n",&f); address of i is 0x7fff52ebc72c address of c is d address of c is 0x7fff52ebc72b address of d is 0x7fff52ebc720 address of f is 0x7fff52ebc71c } return EXIT_SUCCESS;

6 Storage Areas When a program is executed three storage areas are created called segments. Text / Code Segment :- used for the machine code / program instructions including functions. Data Segment (Data + Block Started Symbol + Heap) The Stack Segment :- used for all variables / function variables executed in main

7 High address Command line args argv[0].. argv[n] Stack user Heap BSS Segment Program Data Data Segment Text Segment Program Code kernel OS Kernel (read only) low address

8 Text / Code segment This is where the machine code generated by the compiler lives It is a fixed size (size of our program) and generally read only Usually if an attempt is made to modify data in this segment the program will core dump It is possible to make this position independent for use in shared libraries / DLL s

9 Data Segment BSS Block Started by Symbol This is where global (declared outside main) data that is not assigned a value is stored Also any data prefixed with static and not assigned a default value By default this is assigned zero unless given a default value

10 Data Segment Any data that either global or static but has a predefined value is allocated in the data segment int global1=1; int global2; static float PI=3.141 int main() { static int i=0; static int x; BSS Segment Data Segment set to 0 set to assigned value

11 Stack The stack is where local variables are allocated (automatic variables) This is denoted by the { for scope The data is popped or pushed into the stack following the Last In First Out(LIFO) rule The stack is also used to hold information about functions such as return values and parameters passed (more later) We have little control over the stack

12 Stack Frames When a program calls a function, the function and it s arguments / return point are placed on a stack The function being called may also need local variables to be created on the stack so it will store the initial stack pointer as a frame pointer

13 Stack Pointer main() main () stack frame

14 Stack Pointer return value args main() main () stack frame When we call foo main pushes the arguments for foo onto the stack

15 Stack Pointer foo() foo () stack frame Frame Pointer return value args foo now has a stack for local variables main() main () stack frame Once we have finished foo we replace the stack pointer with the frame pointer

16 stack trace void trace() { void* callstack[128]; int frames = backtrace(callstack, 128); char** strs = backtrace_symbols(callstack, frames); for (int i = 0; i < frames; ++i) { std::cout<<strs[i]<<"\n"; } free(strs); }

17 ./a.out 0 a.out 0x a71f03a _Z5tracev a.out 0x a71f169 main libdyld.dylib 0x00007fff8961b5c9 start + 1 in foo trace() 0 a.out 0x a71f03a _Z5tracev a.out 0x a71f144 _Z3foov a.out 0x a71f16e main libdyld.dylib 0x00007fff8961b5c9 start + 1 in bar trace() 0 a.out 0x a71f03a _Z5tracev a.out 0x a71f11a _Z3bari a.out 0x a71f14e _Z3foov a.out 0x a71f16e main libdyld.dylib 0x00007fff8961b5c9 start + 1

18 recursion A recursive function is a function that can call itself Typical examples are things like calculating factorials or traversing tree like structures It is possible to get a stack overflow using these types of functions

19 int fact( int n ) { trace(); if ( n == 0 ) return 1 ; else return fact( n - 1 ) * n ; } int main() { fact(-1); } 116 a.out 0x ef8 _Z4facti a.out 0x ef8 _Z4facti a.out 0x ef8 _Z4facti a.out 0x ef8 _Z4facti a.out 0x ef8 _Z4facti a.out 0x ef8 _Z4facti a.out 0x ef8 _Z4facti a.out 0x ef8 _Z4facti a.out 0x ef8 _Z4facti a.out 0x ef8 _Z4facti a.out 0x ef8 _Z4facti a.out 0x ef8 _Z4facti + 56 Segmentation fault: 11

20 Heap The heap is used for the programmer to define dynamic memory Data on the heap is anonymous (i.e. not linked to a variable) and the only way we can access it is via a memory address The programmer will then have to manage this data and is one of the most important parts of programming in a non managed language such as C/C++

21 Example Program #include <stdio.h> #include <stdlib.h> int globalvar=0; int func(int _add) { static int stat=0; return stat+=_add; } int main() { int local=0; int i; for(i=0; i<10; ++i) { printf("static = %02d local= %02d global = %02d \n", func(i),local++,globalvar++ ); } return EXIT_SUCCESS; }

22 Program Execution Code Segment.globl _globalvar.zerofill DATA, common,_globalvar,4,2.zerofill DATA, bss,_stat.2777,4,2.section TEXT, cstring,cstring_literals.align 3 L_.str:.asciz "static = %02d local= %02d global = %02d \n".section TEXT, eh_frame,coalesced,no_toc+ strip_static_syms+live_support EH_frame0: Lsection_eh_frame: Leh_frame_common: Lset0 = Leh_frame_common_end-Leh_frame_common_begin.long Lset0 Leh_frame_common_begin:.long 0.byte 1.asciz "zr".byte 1.byte 120.byte 16.byte 1.byte 16.byte 12.byte 7.byte 8.byte 144.byte 1.align 3 Leh_frame_common_end:

23 Arrays Simple data types use a single memory cell to store a variable. It is sometimes more efficient to group data items together in main memory than to allocate an individual memory cell for each variable. A simple way to different fixed amounts of the same data type is by the use of an array. An array is a collection of two or more adjacent cells called array elements associated with a specific symbolic name

24 Array declaration double x[8]; The command above instructs the compiler to allocate 8 double memory cells of type double. These cells will be contiguous (next to each other in a continuous block) This mean accessing them can be done in a sequential manner To access the cells we use an index into the cells starting a 0 for the first index.

25 Array Access To access elements of the array we use the subscript operator [ ] This can be used to get or set the array index value as shown x[0] x[1] x[2] x[3] x[4] x[5] x[6] x[7]

26 Array Manipulation Statement Explanation printf("%.1f ",x[0]); Display the value of x[0] which is 16.0 x[3]=25.0; sum=x[0]+x[1]; sum+=x[2]; x[3]+=1.0 x[2]=x[0]+x[1] Store the value 25.0 in x[3] Store the sum of element x[0] and x[1] into the variable sum Adds x[2] to sum Adds 1 to x[3] Stores the sum of x[0] and x[1] into x[2]

27 Array Initialisation #include <stdio.h> #include <stdlib.h> We can initialise an array in a similar way to a normal variable, the code opposite show this int main() { // array of vowels char vowels[5]={'a','e','i','o','u'}; // the compiler will fill in how many values (25) int primeslt100[]={2,3,5,7,11,13,17,19,23,29,31, 37,41,43,47,53,59,61,67,71,73, 79,83,89,97}; // index to our array int i; // loop and print out the values for(i=0; i<5; ++i) { printf("%c ",vowels[i]); } // newline printf("\n"); // as we don't know how big the primes array is we need // to figure it out, sizeof will return how big the allocated // space is, however it is in bytes and an int takes up // sizeof(int) (usually 4) bytes so we need to div by this } int sizeofarray=sizeof(primeslt100)/sizeof(int); printf("size of array %d\n",sizeofarray); // loop and print for(i=0; i<sizeofarray; ++i) { printf("%d ",primeslt100[i]); } printf("\n"); return EXIT_SUCCESS;

28 Multi-dimensional arrays We can use multi-dimensional arrays to store data in table / tabular format. Whilst this is quite useful for many applications it is still usually more efficient to use a single dimensional array (more in future lectures) The format for declaration is as follows element-type name[size1] [size2]... [sizen];

29 Example If we wished to create an array to store the data for a game of noughts and crosses (tic tac toe for Americans!) We could do the following char XO[3][3]; Column Row 0 X O X 1 O X O XO[1][2] 2 O X X

30 initialising array #include <stdio.h> #include <stdlib.h> int main() { char XO[3][3]={ }; {'-','-','-'}, {'-','-','-'}, {'-','-','-'}, Init all array elements to a - XO[1][2]='O'; int x,y; for(y=0; y<3; ++y) { for(x=0; x<3; ++x) { printf("%c ",XO[y][x]); } printf("\n"); } O } return EXIT_SUCCESS;

31 You can get silly #include <stdio.h> #include <stdlib.h> int main() { int array[4][12][23][5][9][2]; array[0][1][2][3][1][0]=10; printf("%d\n",array[0][1][2][3][1][0]); } return EXIT_SUCCESS; But not recommended!

32 What is a pointer? It's a variable just like any other variable The pointer variable is defined by the asterisk * being placed before the variable name. int *wholenum; What did that just say? Well the variable wholenum is a pointer of type int.

33 But why use Pointers? C and C++ allow the programmer to point into a program and at memory Pointers point to a memory address where a declared variable lives This allows us to create and manipulate dynamic data structures which can grow or shrink depending upon the program need. It also lets us allocate memory on the fly within a program.

34 Pointers and Arrays In C, there is a strong relationship between pointers and arrays, strong enough that pointers and arrays should be discussed simultaneously. Any operation that can be achieved by array subscripting can also be done with pointers. The pointer version will in general be faster but, at least to the uninitiated, somewhat harder to understand. The C Programming Language K&R

35 Pointers and Arrays int a[10]; The definition above declares and array of integers size 10

36 Pointers and Arrays int *pa; pa = &a[0]; The assignment sets pa to point to element zero of a; that is, pa contains the address of a[0].

37 Pointers and Arrays In declarations, [ ] means array of and means pointer to. The assignment x = *pa; will copy the contents of a[0] into x.

38 Pointers and Arrays If pa points to a particular element of an array, then by definition pa+1 points to the next element, pa+i points i elements after pa, and pa-i points i elements before. Thus, if pa points to a[0], *(pa+i) refers to the contents of a[1], pa+i is the address of a[i], and *(pa+i) is the contents of a[i].

39 Pointers and Arrays a reference to a[i] can also be written as *(a+i). In evaluating a[i], C converts it to *(a+i) immediately; the two forms are equivalent. Applying the operator & to both parts of this equivalence, it follows that &a[i] and a+i are also identical: a+i is the address of the i-th element beyond a.

40 What really happens when we create a pointer? Normally a variable directly contains a specific value A pointer contains the (memory) address of a variable that contains a specified value A variable name directly references a value and a pointer indirectly references a value Referencing a value through a pointer is called indirection

41 Remember the Cells? A pointer is used to hold a memory address Whilst all memory address sizes are the same for an operating system The cell size is dependant upon the data type we are pointing to. Hence we give it a data type (int, char float etc) As this will automatically determine the size of the cell we need to manage.

42 int count 4 count directly references a variable whose value is 4 int *countptr int count 4 countptr indirectly references a variable whose value is 4.

43 A simple example #include <stdio.h> #include <stdlib.h> int main() { int i; int *ptri; i=5; printf("i given the value 5 directly i=%d \n",i); // ptri now points to i ptri=&i; // now assign via the indirection *ptri=10; printf("now using the pointer ptri now equals %d\n",i); } return EXIT_SUCCESS;

44 What did that code do? Firstly two variables are declared i a normal integer and *ptri which is a pointer to an integer The first assignment i=5 directly assigned i with the value 5. The second assignment ptri=&i says store the address of the variable i into the variable ptri The final assignment *ptri=10; tells the program to put the value 10 into the memory address pointed to by ptri confused?... Lets look at some pictures

45 With Pictures ptri=&i; 0x100 i 0x102 ptri 0x102 0x104 0x106 0x108 0x10A

46 With Pictures *ptri=10; 0x100 i 10 0x102 ptri 0x102 0x104 0x106 0x108 0x10A

47 void pointers So far we've looked at pointers of the same type e.g. *ptri=i; where both are of type int However this is sometimes not practical So we can use pointers of type void These can assume any data type (with a little help using a process called coercion)

48 A void Pointer Example #include <stdio.h> #include <stdlib.h> int main() { // variables to hold our values int i; char c; float f; // our void pointer void *ptrmorph; // point our pointer to i ptrmorph = &i; *((int *)ptrmorph) =10; i=10 c=c f= // point our pointer to c ptrmorph =&c; *((char *)ptrmorph)='c'; // point our pointer to f ptrmorph=&f; *((float *)ptrmorph)= 25.45f; printf("i=%d c=%c f=%f\n",i,c,f); return EXIT_SUCCESS; }

49 (What (are) all those brackets) for (?) As mentioned we have to tell the pointer what data type we mean it to assume to do this we need the brackets (1) I m a Pointer (2) A float pointer (4)So assign it a value of 25.45f *((float *)ptrmorph)=25.45f; (3)allthough ptrmorph is of type void * I m forcing it to be a float value

50 Why does this work? Remember the cells and the sizeof things! sizeof(void) = 8 (on my 64 bit machine) This is the size of a memory address With the casting we basically get the memory address (always the same size) but take into account the cell size for the actual data type. But why does this matter?

51 Well we can do arithmetic with pointers! YES WE CAN DO MATHS WITH POINTERS! This can lead to confusion however is really powerful and allows us lots of flexibility in coding.

52 Variable Arithmetic Arithmetic on normal variables changes the value contained in the variable This is shown in the following table variable initializer operation result int i=0; i++; i=1 int i=5; i+=5; i=10 int i=10; i--; i=9 int i=10; i-=5; i=5

53 Pointer Arithmetic Arithmetic with pointers take the same form as with other variables as shown #include <stdio.h> #include <stdlib.h> int main() { int intarray[5]={32,65,1,399,9324}; int *ptrtoarray; // as we are using an array we could use // ptrtoarray=intarray; however the following is // more clear when getting the first element ptrtoarray=&intarray[0]; // i for loop for (int i=0; i<5; i++) { printf("intarray value = %d \n",*ptrtoarray); printf("ptrtoarray address= %p \n",ptrtoarray); // increment the pointer to next cell ptrtoarray++; } } return EXIT_SUCCESS;

54 output intarray value = 32 ptrtoarray address= 0x7fff6047d1d4 intarray value = 65 ptrtoarray address= 0x7fff6047d1d8 intarray value = 1 ptrtoarray address= 0x7fff6047d1dc intarray value = 399 ptrtoarray address= 0x7fff6047d1e0 intarray value = 9324 ptrtoarray address= 0x7fff6047d1e4 memory address increments sizeof(int) each time ptrtoarray++ is executed

55 Dynamic memory Allocation When we dynamically allocate memory in a C program we allocate to the heap. This means that the data will be persistent throughout the program lifetime. This means we have to manage this memory ourselves. As the OS allocates the memory for us it is possible that we can run out of memory

56 example #include <stdio.h> #include <stdlib.h> int main() { char *mem; mem=malloc( ); free(mem); return EXIT_SUCCESS; } a.out(33799) malloc: *** mmap(size= ) failed (error code=12) *** error: can't allocate region *** set a breakpoint in malloc_error_break to debug

57 malloc To allocate memory in C we use malloc This allocates size bytes of memory. If the allocation succeeds, a pointer to the block of memory is returned. malloc returns a void pointer (void *), which indicates that it is a pointer to a region of unknown data type. #include <stdlib.h> void * malloc(size_t size); NULL is returned if memory can t be allocated

58 free The memory created by malloc is persistent so needs to be cleared once finished with. This is done with the free function as follows #include <stdlib.h> void free(void *ptr); The pointer must be passed to free only once; unless malloc has been re-called on the same pointer.

59 #include <stdio.h> #include <stdlib.h> Example int main() { char *mem; mem=malloc(10); // free mem free(mem); // double free error free(mem); } return EXIT_SUCCESS; a.out(39525) malloc: *** error for object 0x104a00840: pointer being freed was not allocated *** set a breakpoint in malloc_error_break to debug Abort trap: 6

60 malloc / free The implementation of malloc is not guaranteed to initialise the memory to a set value This can lead to security flaws where we can re-allocate memory and see previous values. In the case of the gcc implementation it seems that the values are set to a zero memory is always allocated contiguously so it can be accessed in the same way as an array as shown in the following example.

61 #include <stdio.h> #include <stdlib.h> int main() { float *mem; mem=malloc(20); for (int i=0; i<20; ++i) { printf("%f ",mem[i]); } printf("\n"); // free up the memory free(mem); return EXIT_SUCCESS; }

62 calloc malloc does not initialise the memory (gcc however does seem to do so) The calloc function however is designed to both allocate memory and set it to zero. #include <stdlib.h> void *calloc(size_t count,size_t size); It allocates count bytes with size data type size float *f = calloc(20,sizeof(float));

63 realloc The realloc function allows us to resize already allocated memory. We can shrink or grow this memory space #include <stdlib.h> void *realloc(void *ptr,size_t size); If realloc is unable to resize the memory region in-place, it allocates new storage then copies the required data. The old pointer is then freed If realloc fails it returns a NULL but the original memory is unaffected

64 #include <stdio.h> #include <stdlib.h> int main() { int index=0; // allocate some memory char *alphabet = calloc(26,sizeof(char)); allocate memory for chars a-z for( char c='a'; c<='z'; ++c) { alphabet[index++]=c; } } for(int i=0; i<26; ++i) { printf("%c ",alphabet[i]); } printf("\nrealloc \n"); alphabet=realloc(alphabet,26*2); for( char c='a'; c<='z'; ++c) { alphabet[index++]=c; } for(int i=0; i<26*2; ++i) { printf("%c ",alphabet[i]); } printf("\n"); return EXIT_SUCCESS; now re-allocate twice as much put upper-case chars in, as index has not change it carries on from where it left off

65 memset #include <string.h> void *memset(void *b int c, size_t len); The memset function set writes len bytes of value c (converted to an unsigned char) to string b It performs a byte to byte copy

66 memcpy #include <string.h> void *memcpy(void *dst, void *src, size_t len); The memcpy function copies len bytes from memory area src to memory area dst. If src and dst over-lap, behaviour is undefined.

67 References Hanly. J. R Koffman E. B. 1999, Problem Solving & Program Design in C, 3rd Edition, Addison Wesley, International Ed Sebesta R. W. 2002, Concepts of Programming Languages, 5th edition, Addison Wesley, International Ed

Lecture 3 Memory and Pointers

Lecture 3 Memory and Pointers Lecture 3 Memory and Pointers Lets think about memory We can think of memory as a series of empty slots Each cell in the slot will hold 1 Byte To identify which cell something is in we need an identifier.

More information

Lecture 2 More C++ Jon Macey

Lecture 2 More C++ Jon Macey Lecture 2 More C++ Jon Macey namespaces namespaces allow us to separate program elements into different named logical units By using namespaces we can declare functions, classes and other code that is

More information

Structured Programming. Jon Macey

Structured Programming. Jon Macey Structured Programming Jon Macey Structured Programming Structured programming is an attempt to formalise the process of program development. There are several basis for a theorem of structured programming,

More information

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

In Java we have the keyword null, which is the value of an uninitialized reference type + More on Pointers + Null pointers In Java we have the keyword null, which is the value of an uninitialized reference type In C we sometimes use NULL, but its just a macro for the integer 0 Pointers are

More information

Lecture 8 Dynamic Memory Allocation

Lecture 8 Dynamic Memory Allocation Lecture 8 Dynamic Memory Allocation CS240 1 Memory Computer programs manipulate an abstraction of the computer s memory subsystem Memory: on the hardware side 3 @ http://computer.howstuffworks.com/computer-memory.htm/printable

More information

From python to C++ part 2. Jon Macey

From python to C++ part 2. Jon Macey From python to C++ part 2 Jon Macey http://nccastaff.bournemouth.ac.uk/jmacey/cppintro jmacey@bournemouth.ac.uk namespaces namespaces allow us to separate program elements into different named logical

More information

Fundamental of Programming (C)

Fundamental of Programming (C) Borrowed from lecturer notes by Omid Jafarinezhad Fundamental of Programming (C) Lecturer: Vahid Khodabakhshi Lecture 9 Pointer Department of Computer Engineering 1/46 Outline Defining and using Pointers

More information

Arrays and Pointers. CSE 2031 Fall November 11, 2013

Arrays and Pointers. CSE 2031 Fall November 11, 2013 Arrays and Pointers CSE 2031 Fall 2013 November 11, 2013 1 Arrays l Grouping of data of the same type. l Loops commonly used for manipulation. l Programmers set array sizes explicitly. 2 Arrays: Example

More information

Memory Management. CSC215 Lecture

Memory Management. CSC215 Lecture Memory Management CSC215 Lecture Outline Static vs Dynamic Allocation Dynamic allocation functions malloc, realloc, calloc, free Implementation Common errors Static Allocation Allocation of memory at compile-time

More information

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

Arrays and Pointers. Arrays. Arrays: Example. Arrays: Definition and Access. Arrays Stored in Memory. Initialization. EECS 2031 Fall 2014. Arrays Arrays and Pointers l Grouping of data of the same type. l Loops commonly used for manipulation. l Programmers set array sizes explicitly. EECS 2031 Fall 2014 November 11, 2013 1 2 Arrays: Example

More information

Programming. Data Structure

Programming. Data Structure Programming & Data Structure For Computer Science & Information Technology By www.thegateacademy.com Syllabus Syllabus for Programming and Data Structures Programming in C, Arrays, Stacks, Queues, Linked

More information

Programming. Pointers, Multi-dimensional Arrays and Memory Management

Programming. Pointers, Multi-dimensional Arrays and Memory Management Programming Pointers, Multi-dimensional Arrays and Memory Management Summary } Computer Memory } Pointers } Declaration, assignment, arithmetic and operators } Casting and printing pointers } Relationship

More information

Content. In this chapter, you will learn:

Content. In this chapter, you will learn: ARRAYS & HEAP Content In this chapter, you will learn: To introduce the array data structure To understand the use of arrays To understand how to define an array, initialize an array and refer to individual

More information

Kurt Schmidt. October 30, 2018

Kurt Schmidt. October 30, 2018 to Structs Dept. of Computer Science, Drexel University October 30, 2018 Array Objectives to Structs Intended audience: Student who has working knowledge of Python To gain some experience with a statically-typed

More information

Heap Arrays. Steven R. Bagley

Heap Arrays. Steven R. Bagley Heap Arrays Steven R. Bagley Recap Data is stored in variables Can be accessed by the variable name Or in an array, accessed by name and index a[42] = 35; Variables and arrays have a type int, char, double,

More information

POINTER AND ARRAY SUNU WIBIRAMA

POINTER AND ARRAY SUNU WIBIRAMA POINTER AND ARRAY SUNU WIBIRAMA Presentation Outline Basic Pointer Arrays Dynamic Memory Allocation Basic Pointer 3 Pointers A pointer is a reference to another variable (memory location) in a program

More information

Memory Management. CS449 Fall 2017

Memory Management. CS449 Fall 2017 Memory Management CS449 Fall 2017 Life9mes Life9me: 9me from which a par9cular memory loca9on is allocated un9l it is deallocated Three types of life9mes Automa9c (within a scope) Sta9c (dura9on of program)

More information

Dynamic memory allocation (malloc)

Dynamic memory allocation (malloc) 1 Plan for today Quick review of previous lecture Array of pointers Command line arguments Dynamic memory allocation (malloc) Structures (Ch 6) Input and Output (Ch 7) 1 Pointers K&R Ch 5 Basics: Declaration

More information

Memory (Stack and Heap)

Memory (Stack and Heap) Memory (Stack and Heap) Praktikum C-Programmierung Nathanael Hübbe, Eugen Betke, Michael Kuhn, Jakob Lüttgau, Jannek Squar Wissenschaftliches Rechnen Fachbereich Informatik Universität Hamburg 2018-12-03

More information

A. Year / Module Semester Subject Topic 2016 / V 2 PCD Pointers, Preprocessors, DS

A. Year / Module Semester Subject Topic 2016 / V 2 PCD Pointers, Preprocessors, DS Syllabus: Pointers and Preprocessors: Pointers and address, pointers and functions (call by reference) arguments, pointers and arrays, address arithmetic, character pointer and functions, pointers to pointer,initialization

More information

Dynamic memory allocation

Dynamic memory allocation Dynamic memory allocation outline Memory allocation functions Array allocation Matrix allocation Examples Memory allocation functions (#include ) malloc() Allocates a specified number of bytes

More information

CS 11 C track: lecture 5

CS 11 C track: lecture 5 CS 11 C track: lecture 5 Last week: pointers This week: Pointer arithmetic Arrays and pointers Dynamic memory allocation The stack and the heap Pointers (from last week) Address: location where data stored

More information

Dynamically Allocated Memory in C

Dynamically Allocated Memory in C Dynamically Allocated Memory in C All throughout the C course (COP 3223), all examples of variable declarations were statically allocated memory. The word static means not changing while the word dynamic

More information

Declaring Pointers. Declaration of pointers <type> *variable <type> *variable = initial-value Examples:

Declaring Pointers. Declaration of pointers <type> *variable <type> *variable = initial-value Examples: 1 Programming in C Pointer Variable A variable that stores a memory address Allows C programs to simulate call-by-reference Allows a programmer to create and manipulate dynamic data structures Must be

More information

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

o Code, executable, and process o Main memory vs. virtual memory Goals for Today s Lecture Memory Allocation Prof. David August COS 217 Behind the scenes of running a program o Code, executable, and process o Main memory vs. virtual memory Memory layout for UNIX processes,

More information

ch = argv[i][++j]; /* why does ++j but j++ does not? */

ch = argv[i][++j]; /* why does ++j but j++ does not? */ CMPS 12M Introduction to Data Structures Lab Lab Assignment 4 The purpose of this lab assignment is to get more practice programming in C, including the character functions in the library ctype.h, and

More information

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

Chapter 14. Dynamic Data Structures. Instructor: Öğr. Gör. Okan Vardarlı. Copyright 2004 Pearson Addison-Wesley. All rights reserved. Chapter 14 Dynamic Data Structures Instructor: Öğr. Gör. Okan Vardarlı Copyright 2004 Pearson Addison-Wesley. All rights reserved. 12-1 Dynamic Data Structure Usually, so far, the arrays and strings we

More information

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

Memory Allocation in C C Programming and Software Tools. N.C. State Department of Computer Science Memory Allocation in C C Programming and Software Tools N.C. State Department of Computer Science The Easy Way Java (JVM) automatically allocates and reclaims memory for you, e.g... Removed object is implicitly

More information

First of all, it is a variable, just like other variables you studied

First of all, it is a variable, just like other variables you studied Pointers: Basics 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 address (rather than the value)

More information

CSCI 2212: Intermediate Programming / C Storage Class and Dynamic Allocation

CSCI 2212: Intermediate Programming / C Storage Class and Dynamic Allocation ... 1/30 CSCI 2212: Intermediate Programming / C Storage Class and Dynamic Allocation Alice E. Fischer October 23, 2015 ... 2/30 Outline Storage Class Dynamic Allocation in C Dynamic Allocation in C++

More information

CS107 Handout 08 Spring 2007 April 9, 2007 The Ins and Outs of C Arrays

CS107 Handout 08 Spring 2007 April 9, 2007 The Ins and Outs of C Arrays CS107 Handout 08 Spring 2007 April 9, 2007 The Ins and Outs of C Arrays C Arrays This handout was written by Nick Parlante and Julie Zelenski. As you recall, a C array is formed by laying out all the elements

More information

Pointers and File Handling

Pointers and File Handling 1 Pointers and File Handling From variables to their addresses Pallab Dasgupta Professor, Dept. of Computer Sc & Engg INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR 2 Basics of Pointers INDIAN INSTITUTE OF TECHNOLOGY

More information

C Pointers. Abdelghani Bellaachia, CSCI 1121 Page: 1

C Pointers. Abdelghani Bellaachia, CSCI 1121 Page: 1 C Pointers 1. Objective... 2 2. Introduction... 2 3. Pointer Variable Declarations and Initialization... 3 4. Reference operator (&) and Dereference operator (*) 6 5. Relation between Arrays and Pointers...

More information

Jagannath Institute of Management Sciences Lajpat Nagar. BCA II Sem. C Programming

Jagannath Institute of Management Sciences Lajpat Nagar. BCA II Sem. C Programming Jagannath Institute of Management Sciences Lajpat Nagar BCA II Sem C Programming UNIT I Pointers: Introduction to Pointers, Pointer Notation,Decalaration and Initialization, Accessing variable through

More information

DAY 3. CS3600, Northeastern University. Alan Mislove

DAY 3. CS3600, Northeastern University. Alan Mislove C BOOTCAMP DAY 3 CS3600, Northeastern University Slides adapted from Anandha Gopalan s CS132 course at Univ. of Pittsburgh and Pascal Meunier s course at Purdue Memory management 2 Memory management Two

More information

Arrays and Memory Management

Arrays and Memory Management Arrays and Memory Management 1 Pointing to Different Size Objects Modern machines are byte-addressable Hardware s memory composed of 8-bit storage cells, each has a unique address A C pointer is just abstracted

More information

Principles of C and Memory Management

Principles of C and Memory Management COMP281 Lecture 8 Principles of C and Memory Management Dr Lei Shi Last Lecture Pointer Basics Previous Lectures Arrays, Arithmetic, Functions Last Lecture Pointer Basics Previous Lectures Arrays, Arithmetic,

More information

Dynamic Memory Allocation (and Multi-Dimensional Arrays)

Dynamic Memory Allocation (and Multi-Dimensional Arrays) Dynamic Memory Allocation (and Multi-Dimensional Arrays) Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2 nd edition, by Kernighan

More information

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

advanced data types (2) typedef. today advanced data types (3) enum. mon 23 sep 2002 defining your own types using typedef today advanced data types (1) typedef. mon 23 sep 2002 homework #1 due today homework #2 out today quiz #1 next class 30-45 minutes long one page of notes topics: C advanced data types dynamic memory allocation

More information

C Review. MaxMSP Developers Workshop Summer 2009 CNMAT

C Review. MaxMSP Developers Workshop Summer 2009 CNMAT C Review MaxMSP Developers Workshop Summer 2009 CNMAT C Syntax Program control (loops, branches): Function calls Math: +, -, *, /, ++, -- Variables, types, structures, assignment Pointers and memory (***

More information

Understanding Pointers

Understanding Pointers Division of Mathematics and Computer Science Maryville College Pointers and Addresses Memory is organized into a big array. Every data item occupies one or more cells. A pointer stores an address. A pointer

More information

Reminder of midterm 1. Next Thursday, Feb. 14, in class Look at Piazza announcement for rules and preparations

Reminder of midterm 1. Next Thursday, Feb. 14, in class Look at Piazza announcement for rules and preparations Reminder of midterm 1 Next Thursday, Feb. 14, in class Look at Piazza announcement for rules and preparations A New Example to see effect of E++ (better than the one in previous lecture) Purpose of showing

More information

ECE551 Midterm Version 2

ECE551 Midterm Version 2 Name: ECE551 Midterm Version 2 NetID: There are 7 questions, with the point values as shown below. You have 75 minutes with a total of 75 points. Pace yourself accordingly. This exam must be individual

More information

Arrays and Pointers in C. Alan L. Cox

Arrays and Pointers in C. Alan L. Cox Arrays and Pointers in C Alan L. Cox alc@rice.edu Objectives Be able to use arrays, pointers, and strings in C programs Be able to explain the representation of these data types at the machine level, including

More information

ECE551 Midterm Version 1

ECE551 Midterm Version 1 Name: ECE551 Midterm Version 1 NetID: There are 7 questions, with the point values as shown below. You have 75 minutes with a total of 75 points. Pace yourself accordingly. This exam must be individual

More information

Dynamic Data Structures. CSCI 112: Programming in C

Dynamic Data Structures. CSCI 112: Programming in C Dynamic Data Structures CSCI 112: Programming in C 1 It s all about flexibility In the programs we ve made so far, the compiler knows at compile time exactly how much memory to allocate for each variable

More information

Heap Arrays and Linked Lists. Steven R. Bagley

Heap Arrays and Linked Lists. Steven R. Bagley Heap Arrays and Linked Lists Steven R. Bagley Recap Data is stored in variables Can be accessed by the variable name Or in an array, accessed by name and index Variables and arrays have a type Create our

More information

(13-2) Dynamic Data Structures I H&K Chapter 13. Instructor - Andrew S. O Fallon CptS 121 (November 17, 2017) Washington State University

(13-2) Dynamic Data Structures I H&K Chapter 13. Instructor - Andrew S. O Fallon CptS 121 (November 17, 2017) Washington State University (13-2) Dynamic Data Structures I H&K Chapter 13 Instructor - Andrew S. O Fallon CptS 121 (November 17, 2017) Washington State University Dynamic Data Structures (1) Structures that expand and contract

More information

C: Pointers. C: Pointers. Department of Computer Science College of Engineering Boise State University. September 11, /21

C: Pointers. C: Pointers. Department of Computer Science College of Engineering Boise State University. September 11, /21 Department of Computer Science College of Engineering Boise State University September 11, 2017 1/21 Pointers A pointer is a variable that stores the address of another variable. Pointers are similar to

More information

C: Pointers, Arrays, and strings. Department of Computer Science College of Engineering Boise State University. August 25, /36

C: Pointers, Arrays, and strings. Department of Computer Science College of Engineering Boise State University. August 25, /36 Department of Computer Science College of Engineering Boise State University August 25, 2017 1/36 Pointers and Arrays A pointer is a variable that stores the address of another variable. Pointers are similar

More information

Introduction to C. Systems Programming Concepts

Introduction to C. Systems Programming Concepts Introduction to C Systems Programming Concepts Introduction to C A simple C Program Variable Declarations printf ( ) Compiling and Running a C Program Sizeof Program #include What is True in C? if example

More information

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

Hacking in C. Memory layout. Radboud University, Nijmegen, The Netherlands. Spring 2018 Hacking in C Memory layout Radboud University, Nijmegen, The Netherlands Spring 2018 A short recap The & operator gives us the address of data Inverse of & is the * operator (dereferencing) 2 A short recap

More information

At this time we have all the pieces necessary to allocate memory for an array dynamically. Following our example, we allocate N integers as follows:

At this time we have all the pieces necessary to allocate memory for an array dynamically. Following our example, we allocate N integers as follows: Pointers and Arrays Part II We will continue with our discussion on the relationship between pointers and arrays, and in particular, discuss how arrays with dynamical length can be created at run-time

More information

Pointers and Arrays. Introduction To Pointers. Using The "Address Of" The Operator & Operator. Using The Dereference. The Operator * Operator

Pointers and Arrays. Introduction To Pointers. Using The Address Of The Operator & Operator. Using The Dereference. The Operator * Operator Introduction To Pointers Pointers and Arrays For : COP 3330. Object oriented Programming (Using C++) http://www.compgeom.com/~piyush/teach/3330 A pointer in C++ holds the value of a memory address A pointer's

More information

CS11001/CS11002 Programming and Data Structures (PDS) (Theory: 3-1-0)

CS11001/CS11002 Programming and Data Structures (PDS) (Theory: 3-1-0) CS11001/CS11002 Programming and Data Structures (PDS) (Theory: 3-1-0) Dynamic Memory Allocation All variables, arrays, structures and unions that we worked with so far are statically allocated, meaning

More information

Arrays and Pointers (part 1)

Arrays and Pointers (part 1) Arrays and Pointers (part 1) CSE 2031 Fall 2012 Arrays Grouping of data of the same type. Loops commonly used for manipulation. Programmers set array sizes explicitly. Arrays: Example Syntax type name[size];

More information

Class Information ANNOUCEMENTS

Class Information ANNOUCEMENTS Class Information ANNOUCEMENTS Third homework due TODAY at 11:59pm. Extension? First project has been posted, due Monday October 23, 11:59pm. Midterm exam: Friday, October 27, in class. Don t forget to

More information

CS24: INTRODUCTION TO COMPUTING SYSTEMS. Spring 2017 Lecture 7

CS24: INTRODUCTION TO COMPUTING SYSTEMS. Spring 2017 Lecture 7 CS24: INTRODUCTION TO COMPUTING SYSTEMS Spring 2017 Lecture 7 LAST TIME Dynamic memory allocation and the heap: A run-time facility that satisfies multiple needs: Programs can use widely varying, possibly

More information

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

Chapter 2 (Dynamic variable (i.e. pointer), Static variable) Chapter 2 (Dynamic variable (i.e. pointer), Static variable) August_04 A2. Identify and explain the error in the program below. [4] #include int *pptr; void fun1() { int num; num=25; pptr= &num;

More information

Hacking in C. Pointers. Radboud University, Nijmegen, The Netherlands. Spring 2019

Hacking in C. Pointers. Radboud University, Nijmegen, The Netherlands. Spring 2019 Hacking in C Pointers Radboud University, Nijmegen, The Netherlands Spring 2019 Allocation of multiple variables Consider the program main(){ char x; int i; short s; char y;... } What will the layout of

More information

MPATE-GE 2618: C Programming for Music Technology. Unit 4.1

MPATE-GE 2618: C Programming for Music Technology. Unit 4.1 MPATE-GE 2618: C Programming for Music Technology Unit 4.1 Memory Memory in the computer can be thought of as a long string of consecutive bytes. Each byte has a corresponding address. When we declare

More information

Dynamic Allocation of Memory Space

Dynamic Allocation of Memory Space C Programming 1 Dynamic Allocation of Memory Space C Programming 2 Run-Time Allocation of Space The volume of data may not be known before the run-time. It provides flexibility in building data structures.

More information

Programs in memory. The layout of memory is roughly:

Programs in memory. The layout of memory is roughly: Memory 1 Programs in memory 2 The layout of memory is roughly: Virtual memory means that memory is allocated in pages or segments, accessed as if adjacent - the platform looks after this, so your program

More information

When you add a number to a pointer, that number is added, but first it is multiplied by the sizeof the type the pointer points to.

When you add a number to a pointer, that number is added, but first it is multiplied by the sizeof the type the pointer points to. Refresher When you add a number to a pointer, that number is added, but first it is multiplied by the sizeof the type the pointer points to. i.e. char *ptr1 = malloc(1); ptr1 + 1; // adds 1 to pointer

More information

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

CS 137 Part 5. Pointers, Arrays, Malloc, Variable Sized Arrays, Vectors. October 25th, 2017 CS 137 Part 5 Pointers, Arrays, Malloc, Variable Sized Arrays, Vectors October 25th, 2017 Exam Wrapper Silently answer the following questions on paper (for yourself) Do you think that the problems on

More information

Pointers (continued), arrays and strings

Pointers (continued), arrays and strings Pointers (continued), arrays and strings 1 Last week We have seen pointers, e.g. of type char *p with the operators * and & These are tricky to understand, unless you draw pictures 2 Pointer arithmetic

More information

Memory Allocation. General Questions

Memory Allocation. General Questions General Questions 1 Memory Allocation 1. Which header file should be included to use functions like malloc() and calloc()? A. memory.h B. stdlib.h C. string.h D. dos.h 2. What function should be used to

More information

CSC 1600 Memory Layout for Unix Processes"

CSC 1600 Memory Layout for Unix Processes CSC 16 Memory Layout for Unix Processes" 1 Lecture Goals" Behind the scenes of running a program" Code, executable, and process" Memory layout for UNIX processes, and relationship to C" : code and constant

More information

Data Structure Series

Data Structure Series Data Structure Series This series is actually something I started back when I was part of the Sweet.Oblivion staff, but then some things happened and I was no longer able to complete it. So now, after

More information

Arrays, Strings, and Pointers

Arrays, Strings, and Pointers Arrays, Strings, and Pointers Jan Faigl Department of Computer Science Faculty of Electrical Engineering Czech Technical University in Prague Lecture 04 BE5B99CPL C Programming Language Jan Faigl, 2017

More information

ECE 15B COMPUTER ORGANIZATION

ECE 15B COMPUTER ORGANIZATION ECE 15B COMPUTER ORGANIZATION Lecture 13 Strings, Lists & Stacks Announcements HW #3 Due next Friday, May 15 at 5:00 PM in HFH Project #2 Due May 29 at 5:00 PM Project #3 Assigned next Thursday, May 19

More information

CS24: INTRODUCTION TO COMPUTING SYSTEMS. Spring 2018 Lecture 6

CS24: INTRODUCTION TO COMPUTING SYSTEMS. Spring 2018 Lecture 6 CS24: INTRODUCTION TO COMPUTING SYSTEMS Spring 2018 Lecture 6 LAST TIME: SYSTEM V AMD64 ABI How to implement basic C abstractions in x86-64? C subroutines with arguments, and local/global variables Began

More information

Intermediate Programming, Spring 2017*

Intermediate Programming, Spring 2017* 600.120 Intermediate Programming, Spring 2017* Misha Kazhdan *Much of the code in these examples is not commented because it would otherwise not fit on the slides. This is bad coding practice in general

More information

Computer Programming Unit 3

Computer Programming Unit 3 POINTERS INTRODUCTION Pointers are important in c-language. Some tasks are performed more easily with pointers such as dynamic memory allocation, cannot be performed without using pointers. So it s very

More information

Reminder: compiling & linking

Reminder: compiling & linking Reminder: compiling & linking source file 1 object file 1 source file 2 compilation object file 2 library object file 1 linking (relocation + linking) load file source file N object file N library object

More information

CS 31: Intro to Systems Pointers and Memory. Kevin Webb Swarthmore College October 2, 2018

CS 31: Intro to Systems Pointers and Memory. Kevin Webb Swarthmore College October 2, 2018 CS 31: Intro to Systems Pointers and Memory Kevin Webb Swarthmore College October 2, 2018 Overview How to reference the location of a variable in memory Where variables are placed in memory How to make

More information

Memory Management. a C view. Dr Alun Moon KF5010. Computer Science. Dr Alun Moon (Computer Science) Memory Management KF / 24

Memory Management. a C view. Dr Alun Moon KF5010. Computer Science. Dr Alun Moon (Computer Science) Memory Management KF / 24 Memory Management a C view Dr Alun Moon Computer Science KF5010 Dr Alun Moon (Computer Science) Memory Management KF5010 1 / 24 The Von Neumann model Memory Architecture One continuous address space Program

More information

CSCI-1200 Data Structures Spring 2016 Lecture 6 Pointers & Dynamic Memory

CSCI-1200 Data Structures Spring 2016 Lecture 6 Pointers & Dynamic Memory Announcements CSCI-1200 Data Structures Spring 2016 Lecture 6 Pointers & Dynamic Memory There will be no lecture on Tuesday, Feb. 16. Prof. Thompson s office hours are canceled for Monday, Feb. 15. Prof.

More information

Array Initialization

Array Initialization Array Initialization Array declarations can specify initializations for the elements of the array: int primes[10] = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 ; initializes primes[0] to 2, primes[1] to 3, primes[2]

More information

Processes. Johan Montelius KTH

Processes. Johan Montelius KTH Processes Johan Montelius KTH 2017 1 / 47 A process What is a process?... a computation a program i.e. a sequence of operations a set of data structures a set of registers means to interact with other

More information

Pointers. Introduction

Pointers. Introduction Pointers Spring Semester 2007 Programming and Data Structure 1 Introduction A pointer is a variable that represents the location (rather than the value) of a data item. They have a number of useful applications.

More information

2-D Arrays. Of course, to set each grid location to 0, we have to use a loop structure as follows (assume i and j are already defined):

2-D Arrays. Of course, to set each grid location to 0, we have to use a loop structure as follows (assume i and j are already defined): 2-D Arrays We define 2-D arrays similar to 1-D arrays, except that we must specify the size of the second dimension. The following is how we can declare a 5x5 int array: int grid[5][5]; Essentially, this

More information

Pointers (2) Applications

Pointers (2) Applications Pointers (2) Applications December 9, 2017 This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported license. 0.1 const qaulifier t1.c #include #include

More information

Introduction to Programming Block Tutorial C/C++

Introduction to Programming Block Tutorial C/C++ Michael Bader Lehrstuhl Informatik V bader@in.tum.de March, 4th March, 8th, 2002 Abstract This is where an abstract might go if you want one. There is usually not a lot of room for much here. C/C++ Tutorial

More information

CSE 333 Lecture 2 Memory

CSE 333 Lecture 2 Memory CSE 333 Lecture 2 Memory John Zahorjan Department of Computer Science & Engineering University of Washington Today s goals - some terminology - review of memory resources - reserving memory - type checking

More information

A process. the stack

A process. the stack A process Processes Johan Montelius What is a process?... a computation KTH 2017 a program i.e. a sequence of operations a set of data structures a set of registers means to interact with other processes

More information

Memory Management I. two kinds of memory: stack and heap

Memory Management I. two kinds of memory: stack and heap Memory Management I two kinds of memory: stack and heap stack memory: essentially all non-pointer (why not pointers? there s a caveat) variables and pre-declared arrays of fixed (i.e. fixed before compilation)

More information

Arrays and Pointers (part 1)

Arrays and Pointers (part 1) Arrays and Pointers (part 1) CSE 2031 Fall 2010 17 October 2010 1 Arrays Grouping of data of the same type. Loops commonly used for manipulation. Programmers set array sizes explicitly. 2 1 Arrays: Example

More information

Pointers (continued), arrays and strings

Pointers (continued), arrays and strings Pointers (continued), arrays and strings 1 Last week We have seen pointers, e.g. of type char *p with the operators * and & These are tricky to understand, unless you draw pictures 2 Pointer arithmetic

More information

Lecture 3: C Programm

Lecture 3: C Programm 0 3 E CS 1 Lecture 3: C Programm ing Reading Quiz Note the intimidating red border! 2 A variable is: A. an area in memory that is reserved at run time to hold a value of particular type B. an area in memory

More information

Dynamic Memory. R. Inkulu (Dynamic Memory) 1 / 19

Dynamic Memory. R. Inkulu  (Dynamic Memory) 1 / 19 Dynamic Memory R. Inkulu http://www.iitg.ac.in/rinkulu/ (Dynamic Memory) 1 / 19 Types of memory allocations auto local * allocated on stack and uninitialized by default * accessible in the function that

More information

C++ for Java Programmers

C++ for Java Programmers Lecture 6 More pointing action Yesterday we considered: Pointer Assignment Dereferencing Pointers to Pointers to Pointers Pointers and Array Pointer Arithmetic 2 Todays Lecture What do we know 3 And now

More information

Basic C Program: Print to stdout. Basic C Program. Basic C Program: Print to stdout. Header Files. Read argument and print. Read argument and print

Basic C Program: Print to stdout. Basic C Program. Basic C Program: Print to stdout. Header Files. Read argument and print. Read argument and print CSC 4304 - Systems Programming Fall 2010 Lecture - II Basics of C Programming Summary of Last Class Basics of UNIX: logging in, changing password text editing with vi, emacs and pico file and directory

More information

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

Pointers (part 1) What are pointers? EECS We have seen pointers before. scanf( %f, &inches );! 25 September 2017 Pointers (part 1) EECS 2031 25 September 2017 1 What are pointers? We have seen pointers before. scanf( %f, &inches );! 2 1 Example char c; c = getchar(); printf( %c, c); char c; char *p; c = getchar();

More information

Memory Allocation in C

Memory Allocation in C Memory Allocation in C When a C program is loaded into memory, it is organized into three areas of memory, called segments: the text segment, stack segment and heap segment. The text segment (also called

More information

CS 31: Intro to Systems Pointers and Memory. Martin Gagne Swarthmore College February 16, 2016

CS 31: Intro to Systems Pointers and Memory. Martin Gagne Swarthmore College February 16, 2016 CS 31: Intro to Systems Pointers and Memory Martin Gagne Swarthmore College February 16, 2016 So we declared a pointer How do we make it point to something? 1. Assign it the address of an existing variable

More information

Today s lecture. Pointers/arrays. Stack versus heap allocation CULTURE FACT: IN CODE, IT S NOT CONSIDERED RUDE TO POINT.

Today s lecture. Pointers/arrays. Stack versus heap allocation CULTURE FACT: IN CODE, IT S NOT CONSIDERED RUDE TO POINT. Pointers/arrays Mechanics, syntax Underlying memory model Array indexing == pointer arithmetic As parameters Stack versus heap allocation Stack declaration, scope, lifetime Heap allocation/deallocation

More information

Ricardo Rocha. Department of Computer Science Faculty of Sciences University of Porto

Ricardo Rocha. Department of Computer Science Faculty of Sciences University of Porto Ricardo Rocha Department of Computer Science Faculty of Sciences University of Porto Adapted from the slides Revisões sobre Programação em C, Sérgio Crisóstomo Compilation #include int main()

More information

Agenda. Peer Instruction Question 1. Peer Instruction Answer 1. Peer Instruction Question 2 6/22/2011

Agenda. Peer Instruction Question 1. Peer Instruction Answer 1. Peer Instruction Question 2 6/22/2011 CS 61C: Great Ideas in Computer Architecture (Machine Structures) Introduction to C (Part II) Instructors: Randy H. Katz David A. Patterson http://inst.eecs.berkeley.edu/~cs61c/sp11 Spring 2011 -- Lecture

More information

Memory Corruption 101 From Primitives to Exploit

Memory Corruption 101 From Primitives to Exploit Memory Corruption 101 From Primitives to Exploit Created by Nick Walker @ MWR Infosecurity / @tel0seh What is it? A result of Undefined Behaviour Undefined Behaviour A result of executing computer code

More information