Question

if so, how do I turn on? I can't find this in the documentation myself and google didn't provide useful results

e.g,

int arr[2];
arr[5] = n;  // runtime error
Was it helpful?

Solution

Yes. The command-line to enable this is -fsanitize=address.

For more information on this, including expected slowdown and why you might be getting link errors, see Clang's AddressSanitizer Documentation.

Keep in mind the address sanitizer does more than bounds check on stack objects; if that's the only capability you want, I think you can limit it to doing only that by additionally passing -mllvm -asan-stack. See this page on address sanitizer flags for details.

OTHER TIPS

No. Unfortunately, even with the -fsanitize=address switch, clang does not prevent abusing a pointer to one object to access data of another object. Consider the following code:

#include <stdio.h>
int main(int argc, char **argv)
{
   char a[4] = "123";
   char b[4] = "ABC";
   int i, k;
   sscanf(argv[1], "%d", &i);
   k = i + (&b[i] - &a[i]);
   printf("a[%d] = '%c'\n", k, a[k]);
   return 0;
}

Save this as badcode.c and compile like this:

clang -fsanitize=address badcode.c -o badcode

Output of a sample run:

$ ./badcode 1
a[17] = 'B'

With real bounds checking, a[17] should be detected as an error.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top