3

I am using gcc (SUSE Linux) 7.2.1 20171020 to compile the following C program strcmp.c:

#include <stdio.h>
#include <string.h>

int main () {
   char str1[] = "e";
   char str2[] = "pi";
   int ret;

   ret = strcmp(str1, str2);

   printf("val: %i\n", ret);

   return(0);
}

I compile this with:

gcc -Wall -Wextra -fsanitize=address  strcmp.c

And when I run it I get:

./a.out
val: -1

This is a surprise to me, I would have expected a result of -11. And indeed I get that when I compile the program in the following way:

gcc -Wall -Wextra  strcmp.c

Why is giving the option -fsanitize=address changing the result?

5
  • 4
    Why would you expect any particular return value from strcmp()? Only its (non)zero-ness and sign are significant, and those are the same for you in both cases. Mar 10, 2018 at 20:18
  • @JohnBollinger, thanks. I think that I have misread man strcmp to expect a "distance". If you make your comment into an answer I'll accept it.
    – user21
    Mar 10, 2018 at 20:34
  • 1
    I think it's still an interesting question to understand how the ASAN "changes" the generated code..
    – P.P
    Mar 10, 2018 at 20:38
  • I agree, @P.P., and that's largely why I commented instead of answering. An answer to the actual question will require analysis of or prior familiarity with glibc implementation details, and I'm afraid I'm not motivated enough to dig into that at the moment. Mar 10, 2018 at 20:57
  • glibc handles strings differently (better) if they are aligned, using word-at-a-time operations. Most probably the -fsanitize=address results in aligned string constants. Mar 10, 2018 at 21:31

1 Answer 1

4

Asan provides a wrapper for strcmp to detect memory overflows. Their version returns only -1, 0 or +1 (which is still standards-compliant).

1
  • 2
    Thanks, at least this taught me to read the strcmp man page more carefully.
    – user21
    Mar 11, 2018 at 18:36

Your Answer

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

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