The below example should crash when calling look_back_1() or look_back_2(). Reason: when negating an unsigned variable the result should remain unsigned.
#include <stdio.h>
int look_back_1(int *arr, unsigned int nmElems, unsigned long dist)
{
int *elem = arr + nmElems;
elem += -dist;
return (*elem);
}
int look_back_2(int *arr, unsigned int nmElems, unsigned int dist)
{
int *elem = arr + nmElems;
elem += -dist;
return (*elem);
}
int main(int argc, char **argv)
{
int arr[100] = { 0, };
printf("1. %d\n", look_back_1(arr, 100, 1)); // <NEEDS TO CRASH, BUT WORKS????>>
printf("2. %d\n", look_back_2(arr, 100, 1)); // <<CRASH!!!!!>>
}
GCC 4.5 crashes in each function call when doing array out of bound access. The compiler emit the NEG opcode for both cases.
GCC 6.1 or Clang will only crash when calling the int version. But they both avoids crashing when they emit the SUB opcode for the unsigned long version.
Are they allowed to do so?