11

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

2 Answers 2

11

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.

4

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.

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.