10

我通过以下方式使用 strcmp

  1. 传递 char[] 数组名
  2. 将指针传递给字符串文字,但第二个导致段错误。尽管我已经确认指针指向正确的字符串文字,但我对为什么会出现段错误感到困惑。这是代码:-

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    int main(int argc, char const *args[])
    {
      char firstName[strlen(*++args)];
      strcpy(firstName, *args);
      char lastName[strlen(*++args)];
      strcpy(lastName, *args);
      printf("%s\t%s\n", firstName, lastName);
    
      printf("%d\n", strcmp(firstName, lastName));// this works
    
      printf("%d\n", strcmp(*(--args),*(++args)));//this gives me a seg fault
    
      return EXIT_SUCCESS;
    }
    

我将它保存为 str.c ,当我编译它时,首先我得到以下警告:

[Neutron@Discovery examples]$ gcc -Wall str.c -o str

str.c: In function ‘main’:
str.c:15: warning: operation on ‘args’ may be undefined

最后运行它,给出如下所示的段错误

[Neutron@Discovery examples]$ ./str Jimmy Neutron


Jimmy   Neutron

-4

Segmentation fault (core dumped)
4

2 回答 2

14

当你将同一个变量作为两个不同的参数传递给同一个函数两次时,不要使用--and 。++

代替printf("%d\n", strcmp(*(--args),*(++args)));

char *first = *(--args);
char *second = *(++args);
printf("%d\n", strcmp(first,second));

仍然不是真正可读的(最好使用索引并检查argc有效性),但至少您不会更改该值并在同一序列点对其进行多次评估。

于 2011-06-10T04:18:00.143 回答
6

In addition to what littleadv's post says, your buffers are one character too short (it didn't leave any space for the null-terminator). Thus, your strcpy causes a buffer overflow.

于 2011-06-10T04:19:06.487 回答