Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Lecture 10:
*&!%[]++
http://www.cs.virginia.edu/cs216
C Bounds Non-Checking
> gcc -o bounds bounds.c
int main (void) { > bounds
int x = 9; abcdefghijkl
char s[4]; s is: abcdefghijkl (User input)
x is: 9
gets(s); > bounds
printf ("s is: %s\n“, s); abcdefghijklm
printf ("x is: %d\n“, x); s is: abcdefghijklmn
} x is: 1828716553
= 0x6d000009
Note: your results > bounds
abcdefghijkln
may vary s is: abcdefghijkln
(depending on x is: 1845493769 = 0x6e000009
machine, compiler, > bounds
aaa... [a few thousand characters]
what else is crashes shell
running, time of
day, etc.). This is What does this kind of mistake
what makes C fun! look like in a popular server?
UVa CS216 Spring 2006 - Lecture 10: Pointers 2
Code Red
Stack Heap
s = “hello”
s
“hello
”
int f (void) {
int s = 1; left side of = is an “lvalue”
it evaluates to a location (address)!
int t = 1; right side of = is an “rvalue”
t = s; it evaluates to a value
t = 2; There is an implicit *
} when a variable is
used as an rvalue!
char s[6];
s[0] = ‘h’; expr1[expr2] in C is just
s[1] = ‘e’; syntactic sugar for
s[2]= ‘l’; *(expr1 + expr2)
s[3] = ‘l’;
s[4] = ‘o’;
s[5] = ‘\0’;
printf (“s: %s\n”, s);
s: hello
char s[6];
*s = ‘h’;
*(s + 1) = ‘e’;
2[s] = ‘l’;
3[s] = ‘l’;
*(s + 4) = ‘o’;
5[s] = ‘\0’;
printf (“s: %s\n”, s);
s: hello
It is undefined!
Windows XP (SP 2)
Windows 2000
(earlier versions of Windows would just crash the whole machine)
http://svn.python.org/view/python/
trunk/Objects/listobject.c
assert (v != NULL);
if (n == INT_MAX) {
PyErr_SetString(PyExc_OverflowError,
"cannot add more objects to list");
return -1;
}
Checks there is
if (list_resize(self, n+1) == -1) enough space to
return -1;
add 1 more element
Py_INCREF(v); (and resizes if
PyList_SET_ITEM(self, n, v);
return 0; necessary)
}
assert (v != NULL);
if (n == INT_MAX) {
PyErr_SetString(PyExc_OverflowError,
"cannot add more objects to list");
return -1;
}
Complicated macro
if (list_resize(self, n+1) == -1) for memory
return -1; management: needs to
Py_INCREF(v); keep track of how many
PyList_SET_ITEM(self, n, v); references there are to
return 0; object v
}