Skip to content

Coding Pitfalls

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 (uint32 i = len arr - 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 (uint32 i = len arr; i > 0; i -= 1) {
  public uint32 n = i - 1;
  // ... do something with arr[n] ...
}
for (uint32 i = 0; i < len arr; i += 1) {
  public uint32 n = len arr - i - 1;
  // ... do something with arr[n] ...
}
Clone this wiki locally