csci 125 lecture 21 martin van bommel. memory allocation variable declarations cause compiler to...
Post on 04-Jan-2016
212 Views
Preview:
TRANSCRIPT
CSci 125
Lecture 21
Martin van Bommel
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
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
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 are if b = 1000
temp[0] = b 1000
temp[1] = b + 8 1008
temp[i] = b + i*8 1000 + i*8
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
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
...
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 accesstemp[index] = value;
• Allows operations on entire array while permitting access based on some index value
Array Application
• Count frequency of occurrence of each decile in a list of course marks
• Create array to store countsint freq[10];
• Initialize arrayfor (i=0; i<10; i++) freq[i] = 0;
• Increment count for each markfreq[mark / 10]++;
top related