C++程序崩溃终端 - 如何调试

C++ program crashes terminal--How do I debug this?

本文关键字:调试 何调试 程序 崩溃 终端 C++      更新时间:2023-10-16

不要问我怎么做——我没有丝毫。

以下代码使我的终端和我使用的任何运行时分析工具崩溃,同时不会引发任何静态检查工具警告。 Valgrind,cppcheck和gdb对我没有什么好处。 g++ -Wall 没有给我任何有用的东西。

该代码的目标是通过 USB 串行连接将字符写入 audrino。 audrino 地址作为第一个参数传递。 传递无符号 int 并将其转换为无符号字符。

#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <termios.h>
#include <iostream>
using namespace std;
int main(int argc,char** argv){
  struct termios stdio;
  int tty_fd;
  unsigned char ctrlChar;
  unsigned int ctrlInt;
  tty_fd=open(argv[1], O_RDWR | O_NONBLOCK);
  tcgetattr(tty_fd, &stdio);
  cfmakeraw(&stdio);
  stdio.c_cc[VMIN]  = 1;
  stdio.c_cc[VTIME] = 0;
  tcsetattr(tty_fd,TCSANOW, &stdio);
  tcsetattr(tty_fd,TCSAFLUSH, &stdio);
  fcntl(tty_fd, F_SETFL, fcntl(STDIN_FILENO, F_GETFL, 0) | O_NONBLOCK);
  cfsetospeed(&stdio,B9600);            // 9600 baud
  cfsetispeed(&stdio,B9600);            // 9600 baud
  cout << "ready on " << argv[1] << endl;
  scanf("%u", ctrlInt);
  cout <<"recieved initial read.n";
  while (ctrlInt < 256){
    ctrlChar = ((char) ctrlInt);
    cout << ctrlInt << ctrlChar << endl;
    write(tty_fd,&ctrlChar,1);
    cout << "sent to audrino.n";
    scanf("%u", ctrlInt);
  }
  cout << "done!" << endl;
  close(tty_fd);
  return 0;
}

现在,如果这看起来很理智,我将提交错误报告。

系统规格:最新的 Arch linux 64 位,使用 "g++ -g -Wall code.c" 编译

如果"崩溃我的终端"是指终端停止工作,那么原因很可能是您在标准输出(又名终端)上将各种标志设置为零。您正在调用tcsetattr()并清零基本上所有终端控制标志。

您应该获取带有 tcgetattr() 的当前终端标志,修改要修改的标志,然后使用该结构调用 tcsetattr() 。不这样做甚至是未定义的行为:

如果 termios_p 指向的 termios 结构的值不是从对fildes tcgetattr()调用的结果派生的,则tcsetattr()的效果是未定义的;应用程序应仅修改此规范在调用tcgetattr()tcsetattr()之间定义的字段和标志, 保留所有其他字段和标志不变。

如果你使用

linux,你可以使用 strace

strace ./yourProgram

您还可以调试核心转储文件,

ulimit -c unlimited
g++ -g ...

比核心转储文件将在程序崩溃时创建。

gdb ./yourProgram coredump

使用bt命令查看崩溃信息。