[英]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中運行此代碼,segement falut(核心轉儲)
在使用gdb時
================================================== ========
程序收到信號SIGSEGV,分段故障。 來自/lib64/libc.so.6的__strcmp_sse42()中的0x0000003b6572fa96
================================================== ========
為什么它不起作用?
如果我鍵入/ bin / ls -al(不帶'&'的任何東西)
buf類型/ bin / ls -al和錯誤
如果輸入&
,則變量argv[cnt-1]
將設置為NULL,因此在if(!strcmp(argv[cnt-1], "exit"))
中,函數strcmp
的第一個參數將為NULL,這會使應用程序崩潰...
此外,您的代碼不檢查任何緩沖區溢出,索引超出范圍,...此代碼相當“危險”
這意味着:
gets
,請參閱https://stackoverflow.com/a/1694042/808101 argv
(注意:此變量名可能不是一個好名字,argv通常是程序本身的參數)數組是否足夠大
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.