Both of the preceding examples could have been detected using a Unix signal handler. In the next example, we will access an array out of bounds, which is undefined in the C++ specification and is a lot more difficult to detect:
int main(void)
{
int numbers[] = {4, 8, 15, 16, 23, 42};
numbers[10] = 0;
}
When executed, we get the following:
As shown in the preceding example, we create an array with 6 elements and then attempt to access the 10th element in the array, which doesn't exist. Attempting to access this element in the array is not guaranteed to generate a segmentation fault. Regardless, UBSAN is capable of detecting this type of error and outputs the issue to stderr on exiting.