C语言 strcmp 行为

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4932848/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 07:44:32  来源:igfitidea点击:

strcmp behaviour

cstringstrcmp

提问by Ashish Vyas

When I run the following code:

当我运行以下代码时:

#include <stdio.h>

int main(int argc, char *argv[])
{
    int p = 0;

    p = strcmp(NULL,"foo");

    return 0;
}

I get segmentation fault. echo $? says 139. But when I run

我得到分段错误。回声 $? 说 139。但是当我跑的时候

#include <stdio.h>

int main(int argc, char *argv[])
{
    int p = 0;

    strcmp(NULL,"foo"); // Note removed assignment

    return 0;
}

I don't get any segmentation fault. Could someone please throw some light?

我没有遇到任何分段错误。有人可以扔点灯吗?

Here is my gcc info:

这是我的 gcc 信息:

> gcc --version
gcc (GCC) 3.4.6 20060404 (Red Hat 3.4.6-8)

回答by Maxim Egorushkin

You are probably using optimization options when compiling. Since the result of strcmp()in the second snippet is ignored the compiler eliminates this function call and this is why your program does not crash. This call can be eliminated only because strcmp()is an intrinsic function, the compiler is aware that this function does not have any side effects.

您可能在编译时使用了优化选项。由于strcmp()第二个片段中的结果被忽略,编译器消除了这个函数调用,这就是你的程序不会崩溃的原因。这个调用可以消除,因为它strcmp()是一个内在函数,编译器知道这个函数没有任何副作用。

回答by unwind

You need to:

你需要:

  • Include the proper headers, or declare functions manually. For strcmp(), you need <string.h>.
  • Not pass an invalid pointer such as NULL to strcmp(), since it doesn't protect against it and will dereference the pointer, thus causing undefined behavior in your program.
  • 包括正确的头文件,或手动声明函数。对于strcmp(),您需要<string.h>
  • 不要将无效的指针(例如 NULL)传递给strcmp(),因为它不会对其进行保护并且会取消引用该指针,从而导致程序中出现未定义的行为。

回答by Benoit

What you are doing is undefined. strcmprequires valid pointers to null-terminated strings.

你在做什么是不确定的。strcmp需要指向以空字符结尾的字符串的有效指针。

NULLis not a pointer to a null-terminated string.

NULL不是指向以空字符结尾的字符串的指针。