Académique Documents
Professionnel Documents
Culture Documents
Alan L. Cox
alc@rice.edu
Objectives
No bounds checking!
Allowed usually causes no error
array[10] may overwrite b
0x1008 a[2]
0x1004 a[1] int a[3];
0x1000 a[0]
0x1014 i
0x1010 c2
0x100C a[2] Could be optimized
a[1] by making these
0x1008
adjacent, and
a[0] reducing padding
0x1004
(by default, not)
0x1000 c1
Array aligned by
size of elements
int array[10];
What is
sizeof(array[3])? 4
returns the size of
an object in bytes
sizeof(array)? 40
0x1014 matrix[1][2]
0x1010 matrix[1][1]
int matrix[2][3];
0x100C matrix[1][0]
0x1008 matrix[0][2]
matrix[1][0] = 17;
0x1004 matrix[0][1]
0x1000 matrix[0][0]
Recall: no bounds checking
matrix[0][3] = 42;
int
function(int n)
{
int array[n];
int *ptr;
Creation
& variable Returns variables memory address
Dereference
* pointer Returns contents stored at address
Indirect assignment
* pointer = val Stores value at address
Assignment
pointer = ptr Stores pointer in another variable
int i1;
int i2;
int *ptr1; 0x1014 0x1000
int *ptr2;
0x1010 ptr2:
i1 = 1; 0x100C 0x1000
i2 = 2; 0x1008 ptr1:
0x1004 i2: 2
3
ptr1 = &i1;
ptr2 = ptr1; 0x1000 i1: 3
1
*ptr1 = 3;
i2 = *ptr2;
*int_ptr1 = int_ptr2;
*int_ptr1 = int2;
What happens?
int1 becomes 8
Cox / Rixner Arrays and Pointers 13
Using Pointers (cont.)
int int1 = 1036; /* some data to point to */
int int2 = 8;
int_ptr1 = *int_ptr2;
int_ptr1 = int_ptr2;
What happens?
p = &a; p = &a;
p += 1; In each, p now points to b p += 1;
(Assuming compiler doesnt
reorder variables in memory)
void
set_x_and_y(int *x,
int *y)
{
*x = 1001;
*y = 1002; a 1001
1
}
b 1002
2
void
f(void)
{ x
int a = 1;
int b = 2; y
set_x_and_y(&a,&b);
}
int
foo(int array[],
unsigned int size)
{
What does this print? 8
printf(%d\n, sizeof(array));
... because array is really
}
a pointer
int
main(void)
{
int a[10], b[5];
foo(a, 10) foo(b, 5) What does this print? 40
printf(%d\n, sizeof(a));
}
C, H e l l o , w o r l d ! \nterminator
C terminator: \0
3
0x1020 argv[4]
2 These are strings!!
0x1018 argv[3] Not integers!
0x1010 argv[2] 1
0x1008 argv[1] hello
0x1000 argv[0]
./program