【问题标题】:linux execve, segmentation fault (strcmp_sse42)linux execve,分段错误(strcmp_sse42)
【发布时间】:2018-05-13 12:05:53
【问题描述】:
#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(任何不带'&'的东西) 干得好

buf 类型 /bin/ls -al & 错误

【问题讨论】:

  • OT:不要使用gets(buf)!请改用fgets(buf, 50, stdin)
  • 无论 Visual Studio 允许什么,来自main() 的唯一有效返回类型是int,而不是void

标签: c linux gdb strcmp execve


【解决方案1】:

如果输入&amp;,变量argv[cnt-1]将被设置为NULL,因此在if(!strcmp(argv[cnt-1], "exit"))函数strcmp的第一个参数将为NULL,这将导致应用程序崩溃...

此外,您的代码不会检查任何缓冲区溢出,索引超出范围,......这段代码非常“危险”

这意味着:

【讨论】:

  • @JongSeokKim 我改进了我的答案,如果我的答案确实解决了您的问题,请验证它。
猜你喜欢
  • 2014-03-17
  • 1970-01-01
  • 2012-11-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多