Presentation is loading. Please wait.

Presentation is loading. Please wait.

CSci 125 Lecture 21 Martin van Bommel. Memory Allocation Variable declarations cause compiler to reserve memory to hold values - allocation Global variables.

Similar presentations


Presentation on theme: "CSci 125 Lecture 21 Martin van Bommel. Memory Allocation Variable declarations cause compiler to reserve memory to hold values - allocation Global variables."— Presentation transcript:

1 CSci 125 Lecture 21 Martin van Bommel

2 Memory Allocation Variable declarations cause compiler to reserve memory to hold values - allocation Global variables –allocated when program begins execution, remain until program exits Local variables in function –allocated upon each call to function –placed in area of memory assigned to this particular invocation of function - frame –frame is deallocated when function returns

3 Size of Allocation Compiler must reserve number of bytes corresponding to size of object –e.g. char - 1 byte int - 2 float - 4 double - 8 sizeof operator gives number of bytes – sizeof (int) is 2 – sizeof x is number of bytes to store x

4 Allocating Arrays double temp[5]; requires 8 bytes/element * 5 elements = 40 Assume stored in frame with base address b Takes bytes b to b + 40 Addresses of elements areif b = 1000 temp[0] = b 1000 temp[1]= b + 8 1008 temp[i] = b + i*8 1000 + i*8

5 Exceeding Array Bounds What if we access temp[7] ? 1000 + 8 * 7 = 1056 But this is outside of bounds of array Most systems do not detect error unless outside bounds of program space (e.g. in OS) Just go ahead and access address 1056 May be another variable or array May even be different data type

6 Preventing Bounds Errors To debug possible error in bounds, use printf –e.g. before accessing temp[i] use printf(”% d\n”, i); To prevent possible error in bounds, use if –e.g. before accessing temp[i] use if (0 > i || i >= MaxElement) printf(”Error in bounds.\n”); else...

7 Array Uses Arrays prove useful because they are ordered structures which allow both –sequential access for (i=0; i<MaxElement; i++) temp[i] = 0; –direct access temp[index] = value; Allows operations on entire array while permitting access based on some index value

8 Array Application Count frequency of occurrence of each decile in a list of course marks Create array to store counts int freq[10]; Initialize array for (i=0; i<10; i++) freq[i] = 0; Increment count for each mark freq[mark / 10]++;


Download ppt "CSci 125 Lecture 21 Martin van Bommel. Memory Allocation Variable declarations cause compiler to reserve memory to hold values - allocation Global variables."

Similar presentations


Ads by Google