Carnegie Mellon
Memory-Related Perils and Pitfalls
Dereferencing bad pointers
Reading uninitialized memory
Overwriting memory
Referencing nonexistent variables Freeing blocks multiple times
Referencing freed blocks
Failing to free blocks
1
Carnegie Mellon
C operators
Operators Associativity
() [] -> .
! ~ ++ + * &(type)sizeof */%
+-
<< >>
< <= > >=
== !=
&
^
|
&&
||
?:
= += -= *= /= %= &= ^= != <<= >>=
,
left to right righttoleft left to right left to right left to right left to right left to right left to right left to right left to right left to right left to right right to left right to left left to right
->, (), and [] have high precedence, with * and & just below Unary +, -, and * have higher precedence than binary forms
Source: K&R page 53
2
Carnegie Mellon
C Pointer Declarations: Test Yourself!
int *p
int *p[13]
int *(p[13])
int **p
int (*p)[13]
int *f()
int (*f)()
p is a pointer to int
p is an array[13] of pointer to int p is an array[13] of pointer to int p is a pointer to a pointer to an int
p is a pointer to an array[13] of int
f is a function returning a pointer to int
f is a pointer to a function returning int
Source: K&R Sec 5.12
3
Carnegie Mellon
Dereferencing Bad Pointers Theclassicscanfbug
int val;
scanf(%d, val);
4
Carnegie Mellon
Reading Uninitialized Memory
Assuming that heap data is initialized to zero
/* return y = Ax */
int *matvec(int **A, int *x) {
int *y = malloc(N*sizeof(int));
int i, j;
}
y[i] += A[i][j]*x[j];
return y;
for (i=0; i
Reviews
There are no reviews yet.