2

I am currently using valgrind-3.10.0.SVN, gcc 4.8.2, and Ubuntu 14.04. This is the code in my file foo.c

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

int main()
{
    char foo[] = "Foo";
    char bar[] = "Bar";
    printf("%d\n", strcmp(foo, bar));
}

I compile with this command:
gcc foo.c -o foo

These are execution commands and outputs:

./foo  
4

valgrind ./foo
1

Why is Valgrind affecting the output of my strcmp() function?

user12205
  • 2,684
  • 1
  • 20
  • 40
zxgear
  • 1,168
  • 14
  • 30

1 Answers1

8

I think valgrind intercepts strcmp, especially it may do that for optimized functions like SSE-optimized ones.

Here's the code of the interceptor:

http://valgrind.sourcearchive.com/documentation/1:3.6.0~svn11254/h__intercepts_8c-source.html

It does return 1:

if ((unsigned char)c1 < (unsigned char)c2) return -1; \
if ((unsigned char)c1 > (unsigned char)c2) return 1; \

glibc, on the other hard, does return a difference:

https://github.com/zerovm/glibc/blob/master/string/strcmp.c

return c1 - c2;

Both implementations are valid, as @retired-ninja said: "strcmp has no guarantees on return value. It is 0, less than zero, or more than zero."

This question is interesting, because, for example, there was one about when strcmp result can be different:

When will strcmp not return -1, 0 or 1?

and many pointed that it can vary on different platforms. But this one shows that it can vary even from run to run if a profiler changes the implementation.

Community
  • 1
  • 1
queen3
  • 15,333
  • 8
  • 64
  • 119