簡體   English   中英

在堆上分配數組時出現分段錯誤

[英]Segmentation fault when allocating array on the heap

假設我在堆上聲明了一個大小超過堆限制的全局數組。 當然會拋出分段錯誤。 我的問題是,當我們這樣做時會發生什么? 額外的整數會覆蓋我們計算機系統中的某些部分嗎?

這取決於您使用的操作系統(如果有)。

提供進程虛擬機抽象的系統 - 即任何 *nix 變體、Windows、一些 RTOS,例如 QNX

在這些系統中,虛擬 memory(地址空間)和提交的物理頁面之間存在區別。 當寫入關聯的虛擬地址空間時,該進程獲得物理頁面。 因此,可以分配比系統上物理 memory 更大的堆塊,並且堆可以按需增長。 系統可以使用分頁來維護由實際 memory 支持的工作頁面集,並將無法容納的頁面寫入磁盤。 這就是許多人(錯誤地)描述為“虛擬內存”的東西。 值得注意的是,iOS、Android 和許多嵌入式系統沒有尋呼機。

如果操作系統濫用 memory ,操作系統可能會殺死您的進程 - 例如,分配一個巨大的堆塊,然后隨機寫入所有堆塊。 操作系統可能會對進程可以擁有的虛擬地址空間或物理頁數施加限制,並在超過此限制時終止進程。

超出堆塊的末尾是 C 中的未定義行為 這可能會產生異常 - 或任何其他意外后果。 此時您是否也超出了整個堆,這是一個有爭議的問題。

所有這些操作系統都將防止系統 memory 被進程破壞。

裸機系統,一些嵌入式操作系統

這些系統缺乏進程虛擬機抽象和與之配套的 memory 保護; 它們缺少分頁,並且通常不允許分配比物理頁面中所能容納的更大的堆塊。 覆蓋已分配塊的末尾將具有未定義的行為。

假設我在堆上聲明了一個大小超過堆限制的全局數組。

您不能在堆上聲明全局數組,因為您在編譯時無權訪問此 memory。

Probably you mean the array with the static storage duration and if the size of it will be larger than the memory reserved for the static storage duration objects the linker will throw the error.

memory 只能使用malloc系列函數動態分配運行時。

int a[500]; // 'a' is a static storage duration object

int foo()
{
   int b[500]; //'b' is an automatic storage duration object (most implementations use stack for it)
   static int c[500]; // 'c' is a static storage duration object
   int *d; //'d' is an automatic storage duration pointer (most implementations use 

   d = malloc(1000); // 'd' references the 1000 byte memory area allocated on the heap
}

如果您嘗試分配的 memory 比可用的多,則分配 function 將返回NULL但不會失敗。 如果您嘗試訪問不屬於 object 的 memory - 這是未定義的行為,可能會導致分段錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM