c - Valgrind 弄乱了 strcmp() 的返回值,为什么?

标签 c gcc valgrind

我目前使用的是 valgrind-3.10.0.SVN、gcc 4.8.2 和 Ubuntu 14.04。这是我的文件 foo.c

中的代码
#include <stdio.h>
#include <string.h>

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

我用这个命令编译:
gcc foo.c -o foo

这些是执行命令和输出:

./foo  
4

valgrind ./foo
1

为什么 Valgrind 会影响我的 strcmp() 函数的输出?

最佳答案

我认为 valgrind 会拦截 strcmp,尤其是它可能会针对优化函数(如 SSE 优化函数)执行此操作。

拦截器代码如下:

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

它确实返回 1:

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

另一方面,glibc 确实返回了一个差异:

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

return c1 - c2;

这两种实现都是有效的,正如@retired-ninja 所说:“strcmp 不能保证返回值。它是 0、小于零或大于零。”

这个问题很有趣,因为,例如,有一个关于 strcmp 结果何时可能不同的问题:

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

许多人指出它在不同平台上可能会有所不同。但这表明,如果探查器更改实现,它甚至会因运行而异。

关于c - Valgrind 弄乱了 strcmp() 的返回值,为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29486198/

相关文章:

c - valgrind 使用 getline 函数报告内存丢失

c++ - 将 std::string 数据的深层拷贝存储到 std::vector

c - 有时在保存有条件分配的内存的指针上使用free时程序崩溃

c - 缩短线程安全(不平衡)二叉树中的关键部分

c - 如何正确为接收矩阵的 C 函数创建 header

c - C 中的引用计数和函数内部分配的内存

c++ - g++和gcc有什么区别?

c - 汇编代码 fsqrt 和 fmul 指令

c - 使用 Valgrind 进行程序调试

c - 从LabVIEW数组中获取内存地址