strcmp 的段错误
我按以下方式使用 strcmp
- 传递 char[] 数组名称
传递指向字符串文字的指针 但是,第二个结果导致段错误。尽管我已经确认指针指向正确的字符串文字,但我很困惑为什么会出现段错误。 这是代码:-
#include
; #include ; #include ; int main(int argc, char const *args[]) { char 第一个名称[strlen(*++args)]; strcpy(名字, *args); char 姓氏[strlen(*++args)]; strcpy(姓氏, *args); printf("%s\t%s\n", 名字, 姓氏); printf("%d\n", strcmp(firstName, lastName));// 这有效 printf("%d\n", strcmp(*(--args),*(++args)));//这给了我一个段错误 返回退出_成功; }
我将其保存为 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
最后运行它,给出一个 seg 错误,如下所示
[Neutron@Discovery examples]$ ./str Jimmy Neutron
Jimmy Neutron
-4
Segmentation fault (core dumped)
I am using strcmp in following ways
- Passing char[] array names
Passing pointers to string literals
but, the second result in seg fault. even though i have confirmed that pointers point to correct string literals, i am confused as to why i am getting seg fault..
Here is the code:-#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; }
I am saving it as str.c and when i compile it, first i get following warning:
[Neutron@Discovery examples]$ gcc -Wall str.c -o str
str.c: In function ‘main’:
str.c:15: warning: operation on ‘args’ may be undefined
finally running it, gives a seg fault as shown below
[Neutron@Discovery examples]$ ./str Jimmy Neutron
Jimmy Neutron
-4
Segmentation fault (core dumped)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当您将同一个变量作为两个不同的参数两次传递给同一个函数时,请勿使用
--
和++
。而不是
printf("%d\n", strcmp(*(--args),*(++args)));
仍然
不真正可读(最好使用索引并检查
argc
的有效性),但至少您不会更改该值并在同一序列点对其进行多次评估。Don't use
--
and++
when you pass the same variable to the same function twice as two different parameters.Instead of
printf("%d\n", strcmp(*(--args),*(++args)));
do
Still not really readable (better use indexes and check against
argc
for validity), but at least you don't change the value and evaluate multiple times it at the same sequence point.除了 Littleadv 的帖子所说的之外,您的缓冲区还太短了一个字符(它没有为空终止符留下任何空间)。因此,您的
strcpy
会导致缓冲区溢出。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.