段錯誤(Segment Fault)

1.什麼是段錯誤(Segmemt Fault)

A segmentation fault (often shortened to segfault) is a particular error condition that can occur during the operation of computer software. In short, a segmentation fault occurs when a program attempts to access a memory location that it is not allowed to access, or attempts to access a memory location in a way that is not allowed (e.g., attempts to write to a read-only location, or to overwrite part of the operating system). Systems based on processors like the Motorola 68000 tend to refer to these events as Address or Bus errors.

Segmentation is one approach to memory management and protection in the operating system. It has been superseded by paging for most purposes, but much of the terminology of segmentation is still used, "segmentation fault" being an example. Some operating systems still have segmentation at some logical level although paging is used as the main memory management policy.

On Unix-like operating systems, a process that accesses invalid memory receives the SIGSEGV signal. On Microsoft Windows, a process that accesses invalid memory receives the STATUS_ACCESS_VIOLATION exception.

所謂的段錯誤 就是指訪問的內存超出了系統所給這個程序的內存空間,通常這個值是由gdtr來保存的,他是一個48位的寄存器,其中的32位是保存由它指向的gdt表, 後13位保存相應於gdt的下標,最後3位包括了程序是否在內存中以及程序的在cpu中的運行級別,指向的gdt是由以64位爲一個單位的表,在這張表中 就保存着程序運行的代碼段以及數據段的起始地址以及與此相應的段限和頁面交換還有程序運行級別還有內存粒度等等的信息。一旦一個程序發生了越界訪 問,cpu就會產生相應的異常保護,於是segmentation fault就出現了

通過上面的解釋,段錯誤應該就是訪問了不可訪問的內存,這個內存區要麼是不存在的,要麼是受到系統保護的。

2.如何處理

可以通過gdb結合gcc來調試產生段錯誤的程序。
可以通過man 7 signal查看SIGSEGV的信息。

3.注意
<1>定義了指針後記得初始化,在使用的時候記得判斷是否爲NULL
<2>在使用數組的時候是否被初始化,數組下標是否越界,數組元素是否存在等
<3>在變量處理的時候變量的格式控制是否合理等

 

 

參考:
1.https://www.cnblogs.com/joeblackzqq/archive/2011/04/11/2012318.html

2.https://blog.csdn.net/qq_29350001/article/details/53780697

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章