【问题标题】:Illegal Instruction :4非法指令:4
【发布时间】:2021-06-14 12:07:17
【问题描述】:

我正在编写一个用于执行终端“历史 10”命令的 c 代码,我在我的 mac 终端上使用 clang 编译器运行程序,它显示错误“非法指令:4” 我的代码是-

#include <stdio.h> 
#include <stdlib.h> 
#include <fcntl.h> 
#include<errno.h> 
#include<sys/wait.h> 
#include <unistd.h> 
#include<string.h>
int main()
{  char cmd[10];
   strcpy(cmd,"history 10");
       system(cmd); 
    return 0;
} 

【问题讨论】:

  • 您需要char cmd[11]; 否则不会存储NUL 字符('\0')。
  • Off-by-one 错误。 (不要吝啬缓冲区大小......)
  • 让编译器完成工作:char cmd[] = "history 10";
  • 请不要同时使用标签cc++。这些是不同的语言,您的代码是纯 C 语言,
  • 您确定需要包含所有这些*.h 文件吗?

标签: c++ c macos terminal


【解决方案1】:

你溢出了你的缓冲区:cmd 数组只有 10 个字符,而你 strcpy 一个 11 个字符的字符串到其中(字符串末尾有一个隐含的第 11 个零字节,这是字符串的终止符) .

摆脱缓冲区,然后做

 system("history 10"); 

或者声明缓冲区足够长以容纳您当前的,可能还有未来的一些命令。像这样的:

char cmd[500];

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-15
    • 2018-03-20
    • 2017-09-10
    • 1970-01-01
    • 2015-01-09
    • 2018-07-20
    • 2019-03-11
    • 2022-01-16
    相关资源
    最近更新 更多