Core Dump/Segmentation fault是访问“不属于您”的内存时导致的一种特定错误
null
- 当一段代码试图在内存中的只读位置或释放的内存块中执行读写操作时,它被称为核心转储。
- 这是一个指示内存损坏的错误。
常见分段故障场景:
- 修改字符串文字: 以下程序可能会崩溃(给出分段错误),因为行*(str+1)=“n”试图写入只读存储器。
C
int main() { char *str; /* Stored in read only part of data segment */ str = "GfG" ; /* Problem: trying to modify read only memory */ *(str+1) = 'n' ; return 0; } |
Abnormal termination of program.
参考 C语言中字符串的存储 详情
- 访问已释放的地址: 在下面的代码中,指针p在释放内存块后被解除引用,这是编译器不允许的。因此,它会在运行时产生错误段故障或程序异常终止。 例子:
C++
// C++ program to illustrate // Core Dump/Segmentation fault #include <iostream> using namespace std; int main( void ) { // allocating memory to p int * p = ( int *) malloc (8* sizeof ( int )); *p = 100; // deallocated the space allocated to p free (p); // core dump/segmentation fault // as now this statement is illegal *p = 110; return 0; } // This code is contributed by shivanisinghss2110 |
C
// C program to illustrate // Core Dump/Segmentation fault #include <stdio.h> #include<alloc.h> int main( void ) { // allocating memory to p int * p = malloc (8); *p = 100; // deallocated the space allocated to p free (p); // core dump/segmentation fault // as now this statement is illegal *p = 110; return 0; } |
输出:
Abnormal termination of program.
- 访问数组索引外边界:
CPP
// C++ program to demonstrate segmentation // fault when array out of bound is accessed. #include <iostream> using namespace std; int main() { int arr[2]; arr[3] = 10; // Accessing out of bound return 0; } |
输出:
Abnormal termination of program.
- scanf()使用不当: scanf()函数需要一个变量的地址作为输入。在这个程序中 值为2,并假定其地址为1000。如果我们将n传递给scanf(),则从STDIN获取的输入将被放入无效内存2中,而该内存应该是1000。这是一种导致分段错误的内存损坏。
C++
// C++ program to demonstrate segmentation // fault when value is passed to scanf #include <iostream> using namespace std; int main() { int n = 2; cin >> " " >> n; return 0; } // This code is contributed by shivanisinghss2110 |
C
// C program to demonstrate segmentation // fault when value is passed to scanf #include <stdio.h> int main() { int n = 2; scanf ( " " ,n); return 0; } |
输出:
Abnormal termination of program.
- 堆栈溢出 这不是指针相关的问题,即使代码可能没有单个指针。这是因为递归函数被反复调用,这会耗尽所有堆栈内存,导致堆栈溢出。堆栈内存不足也是一种内存损坏。它可以通过从递归函数返回一个基本条件来解决。
- 取消对未初始化指针的引用 指针必须指向有效内存才能访问它。
C++14
// C++ program to demonstrate segmentation // fault when uninitialized pointer is accessed. #include <iostream> using namespace std; int main() { int * p; cout << *p; return 0; } // This code is contributed by Mayank Tyagi |
C
// C program to demonstrate segmentation // fault when uninitialized pointer is accessed. #include <stdio.h> int main() { int *p; printf ( "%d" ,*p); return 0; } |
本文由 比沙尔·库马尔·杜比 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 写极客。组织 或者把你的文章寄去评论-team@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。 如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END