C++文档阅读笔记-Core Dump (Segmentation fault) in CC++

C++文档阅读笔记-Core Dump (Segmentation fault) in CC++,第1张

这篇博文比较有意思,在此记录下,方便以后查阅,同样也是在GeeksForGeeks看读到的。

Core Dump/Segmentation fault这个报错是内存在告诉程序员“这块内存不属于你”。

  1. 代码试图在只读内存上进行读写 *** 作,或者在释放过的内存上进行读写 *** 作就会出现core dump。
  2. 这个错误代码内存受到了破坏。

常见的Segmentaion fault场景

修改了字符串上的某字节

如下面的代码,程序会奔溃,错误类型是segmentation fault error,因为使用*(str + 1) = 'n'去修改只读内存。

// C++ program to demonstrate segmentation fault/core dump
// by modifying a string literal

#include 
using namespace std;

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;
}

// This code is contributed by sarajadhav12052009

输出如下:

Abnormal termination of program.

访问被释放过的内存

如下代码,指针p对变量进行了free,但再对个指针变量进行*赋值时,编译不会报错,但运行时会报错。

// C++ program to illustrate
// Core Dump/Segmentation fault
#include 
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

输出:

Abnormal termination of program.

访问数组下标越界

代码如下:

// C++ program to demonstrate segmentation
// fault when array out of bound is accessed.
#include 
using namespace std;
 
int main()
{
   int arr[2];
   arr[3] = 10;  // Accessing out of bound
   return 0;
}

输出:

Abnormal termination of program.

错误使用scanf/cin

比如输入了空格啥的,如下代码:

// C++ program to demonstrate segmentation
// fault when value is passed to scanf
#include 
using namespace std;
 
 
int main()
{
   int n = 2;
   cin >> " " >> n;
   return 0;
}
 
// This code is contributed by shivanisinghss2110

输出:

Abnormal termination of program.
栈溢出

这种一般是程序代码有问题,造成的Core Dump,比如在递归函数中,出现问题,因为在运行时,函数会进行大量的入栈 *** 作, *** 作栈区空间浪费,最后栈区都满了。所以这种问题一般是代码逻辑错误。

使用了未初始化的指针

一个指针没有分配内存,但代码中依旧去访问这块空间,代码如下:

// C++ program to demonstrate segmentation
// fault when uninitialized pointer is accessed.
#include 
using namespace std;
 
int main()
{
    int* p;
    cout << *p;
    return 0;
}
// This code is contributed by Mayank Tyagi

欢迎分享,转载请注明来源:内存溢出

原文地址:https://www.54852.com/langs/2889800.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-09-14
下一篇2022-09-14

发表评论

登录后才能评论

评论列表(0条)

    保存