You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
scauligi edited this page Mar 19, 2018
·
1 revision
Remember both C and FaCT are not memory safe (we're working on it!). Here are some pitfalls to avoid when writing code.
Reverse loops
When writing a loop counting backwards, you might be tempted to write something like this:
for (uint32i=lenarr-1; i >= 0; i-=1) {
// ... do something with arr[i] ...
}
The problem is that after i reaches 0 and is decremented, it wraps around to UINT32_MAX. When the loop performs the comparison, it finds the UINT32_MAX is still greater than 0, and so the loop attempts to access arr[UINT32_MAX] and segfaults.
Here are two alternative patterns you can use instead:
for (uint32i=lenarr; i>0; i-=1) {
publicuint32n=i-1;
// ... do something with arr[n] ...
}
for (uint32i=0; i<lenarr; i+=1) {
publicuint32n=lenarr-i-1;
// ... do something with arr[n] ...
}