linux 执行,分段错误 (strcmp_sse42)
linux execve, segmentation fault (strcmp_sse42)
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
void main(){
int x,y,status, i;
int cnt = 0;
int flag = 0;
char buf[50];
char str[50];
char * argv[10];
char * ptr;
for(i=0; i<10; i++){
printf("$");
gets(buf);
strcpy(str, buf);
ptr = strtok(buf, " ");
while(ptr != NULL){
argv[cnt] = ptr;
cnt++;
ptr = strtok(NULL," ");
}
if(!strcmp(argv[cnt-1], "&")) {
argv[cnt-1] = 0;
flag = 1;
}
else {
argv[cnt] = 0;
}
if(!strcmp(argv[cnt-1], "exit")) exit(0);
x=fork();
if (x==0){
sleep(1);
printf("I am child to execute %s\n", str);
y=execve(argv[0], argv, 0);
if (y<0){
perror("exec failed");
exit(1);
}
}
else {
if(flag == 0) {
wait(&status);
}
}
flag = 0;
cnt = 0;
}
}
运行 这段代码在 linux 那么,
段错误(核心转储)
同样在使用 gdb 时,
=========================================== =============
程序收到信号SIGSEGV,
分段故障。
__strcmp_sse42 () 中的 0x0000003b6572fa96
来自 /lib64/libc.so.6
=========================================== =============
为什么不起作用?
如果我输入
/bin/ls -al(没有'&'的任何东西)
干得好
缓冲区类型
/bin/ls-阿尔&
错误
如果输入 &
,变量 argv[cnt-1]
将被设置为 NULL,因此在 if(!strcmp(argv[cnt-1], "exit"))
中,函数 strcmp
的第一个参数将为 NULL,这将使应用程序崩溃...
此外,您的代码不检查任何缓冲区溢出、索引越界...这段代码非常"dangerous"
这意味着:
- 你不应该使用
gets
,请参阅
- 检查
argv
(注意:这个变量名可能不太好,argv 通常是程序本身的参数)插入元素时数组足够大
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
void main(){
int x,y,status, i;
int cnt = 0;
int flag = 0;
char buf[50];
char str[50];
char * argv[10];
char * ptr;
for(i=0; i<10; i++){
printf("$");
gets(buf);
strcpy(str, buf);
ptr = strtok(buf, " ");
while(ptr != NULL){
argv[cnt] = ptr;
cnt++;
ptr = strtok(NULL," ");
}
if(!strcmp(argv[cnt-1], "&")) {
argv[cnt-1] = 0;
flag = 1;
}
else {
argv[cnt] = 0;
}
if(!strcmp(argv[cnt-1], "exit")) exit(0);
x=fork();
if (x==0){
sleep(1);
printf("I am child to execute %s\n", str);
y=execve(argv[0], argv, 0);
if (y<0){
perror("exec failed");
exit(1);
}
}
else {
if(flag == 0) {
wait(&status);
}
}
flag = 0;
cnt = 0;
}
}
运行 这段代码在 linux 那么, 段错误(核心转储)
同样在使用 gdb 时,
=========================================== =============
程序收到信号SIGSEGV, 分段故障。 __strcmp_sse42 () 中的 0x0000003b6572fa96 来自 /lib64/libc.so.6
=========================================== =============
为什么不起作用?
如果我输入 /bin/ls -al(没有'&'的任何东西) 干得好
缓冲区类型 /bin/ls-阿尔& 错误
如果输入 &
,变量 argv[cnt-1]
将被设置为 NULL,因此在 if(!strcmp(argv[cnt-1], "exit"))
中,函数 strcmp
的第一个参数将为 NULL,这将使应用程序崩溃...
此外,您的代码不检查任何缓冲区溢出、索引越界...这段代码非常"dangerous"
这意味着:
- 你不应该使用
gets
,请参阅 - 检查
argv
(注意:这个变量名可能不太好,argv 通常是程序本身的参数)插入元素时数组足够大