聊聊段错误(一)

2023-11-13 20:24:18 浏览数 (2)

先说下周二晚上一个有意思的事情——大娃的U盘和移动硬盘中病毒了,文件查看不到,只留下一个无法运行的.exe文件,使用360 U助手能扫描到文件。本来按照官方教程准备备份数据,欲摆开架势开干,然后看流程还挺复杂的,就拿U盘小试牛刀,结果失败了。问题不大,失败不是常有的嘛~于是放弃了,开始谷歌,开始漫漫尝试。最终在试了两三次之后,使用管理员权限,运行解除隐藏文件的命令,将文件重新恢复显示。

然后有了这样一个问题:为什么U盘不带防火墙?我平常主要使用Linux系统开发,是在Windows上装的虚拟机,由于工作需要,装了10个虚拟机。。。当然了,有几个是“过程虚拟机”,学会之后要删掉的。平时一些软件需要,我的防火墙都是关闭的,感觉病毒威胁还好。。再之前ubuntu的ssh端口使用了默认端口,被病毒入侵开始挖矿,大概就这些了。说回U盘防火墙,以自己的理解,它是一个被挂载的设备,本身没有运行能力,需要其他宿主来加载,有点类似一个库。

以下所述均主要在Linux平台。

以目前所接触的编程来看,尤其稍大一点儿的UI程序,偶尔操作就会发生闪退,这块不一定是段错误。闪退不一定是段错误,但段错误一定会崩。

先追溯一些历史:

Stackoverflow:What is a segmentation fault?

What is a segmentation fault? Is it different in C and C ? How are segmentation faults and dangling pointers related?

Segmentation fault is a specific kind of error caused by accessing memory that “does not belong to you.” It’s a helper mechanism that keeps you from corrupting the memory and introducing hard-to-debug memory bugs. Whenever you get a segfault you know you are doing something wrong with memory – accessing a variable that has already been freed, writing to a read-only portion of the memory, etc. Segmentation fault is essentially the same in most languages that let you mess with memory management, there is no principal difference between segfaults in C and C .

There are many ways to get a segfault, at least in the lower-level languages such as C( ). Acommon way to get a segfault is to dereference a null pointer:

代码语言:javascript复制
int *p = NULL;
*p = 1;

Another segfault happens when you try to write to a portion of memory that was marked as read-only:

代码语言:javascript复制
char *str = "Foo"; // Compiler marks the constant string as read-only
*str = 'b'; // Which means this is illegal and results in a segfault

Dangling pointer points to a thing that does not exist anymore, like here:

代码语言:javascript复制
char *p = NULL;
{
    char c;
    p = &c;
}// Now p is dangling

The pointer p dangles because it points to the character variable c that ceased to exist after the block ended. And when you try to dereference dangling pointer (like *p='A'), you would probably get a segfault.

上述资料仅用于交流学习,勿商用。

文章仅讨论软件引发的段错误。

简单概述,段错误是访问本来你不应该访问的区域,像只读数据段进行写操作,对空指针进行赋值操作等。

对于编程序的人来说,必现的错误不难解决,难解决的是偶发的问题。一些设备销售出去,当发生闪退时,可以记录闪退位置,如果频繁发生一些问题,软件可以用debug模式编译。更具较优的选择可能是自动化测试,防患于未然。本次先抛砖引玉,下次使用具体例子展示如何记录段错误信息。

喜欢分享,我是大贺!

0 人点赞