Skip to content

Instantly share code, notes, and snippets.

@elliott-beach
Last active September 14, 2017 22:36
Show Gist options
  • Save elliott-beach/f73ab2d0e82966e7e878bcbff86f63a1 to your computer and use it in GitHub Desktop.
Save elliott-beach/f73ab2d0e82966e7e878bcbff86f63a1 to your computer and use it in GitHub Desktop.
Problem 4
/*
Here’s a function that’s intended to reverse the order of a subsequence of integers within an
array. For instance suppose the array a originally contains the integers 1 2 3 4 5 6 7 8 9. If
you call reverse_range(a, 2, 5), the afterwards the array a will contain the same integers but
with the ones in positions 2 through 5 (counting from zero) in the opposite order. I.e., a will be 1
2 6 5 4 3 7 8 9.
Unfortunately you’ll see that this function was not implemented very carefully.
*/
/*
Describe at least three bad things that could happen when running this function in situations
that the programmer probably didn’t think of. For each case, identify the programming
mistake, the problematic situation, and the bad outcome.
*/
/* Reverse the elements from FROM to TO, inclusive */
void reverse_range(int *a, int from, int to) {
int *p = &a[from];
int *q = &a[to];
/* Until the pointers move past each other: */
while (!(p == q + 1 || p == q + 2)) {
/* Swap *p with *q, without using a temporary variable */
*p += *q; /* *p == P + Q */
*q = *p - *q; /* *q == P + Q - Q = P */
*p = *p - *q; /* *p == P + Q - P = Q */
/* Advance pointers towards each other */
p++;
q--;
}
}
@elliott-beach
Copy link
Author

elliott-beach commented Sep 14, 2017

Problems include:

  1. if arr is passed with to >= from, the loop will never terminate resulting in a buffer overflow.
  2. Swaps middle element with itself - simply incorrect behavior.
  3. Array is modified concurrently while the elements are being swapped, then the result will be garbage.
    Also, from or to could be negative, but I feel like we should let the programmer do that if they want to?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment