Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> 關於 Linux

C 語言指標操作導致 Segmentation fault?正確分配記憶體避免非法存取

編輯:關於 Linux

錯誤範例

char *c1;
for (i=0; i

c1 未初始化,指向隨機位址,寫入導致 Segmentation fault。

正確做法

char *c1 = malloc(n);   // 先分配 n 位元組
if (c1) {
    for (i=0; i

核心觀念

  • 指標使用前必須指向合法記憶體(malloc、calloc、陣列位址)。
  • 釋放後指標應設為 NULL,避免野指標。

結語

Segmentation fault 多半源於「指向錯誤記憶體」,落實「先分配、再使用、後釋放」即可避免 90% 此類錯誤。

Copyright © Windows教程網 All Rights Reserved