C++中段错误的常见情况

C++中段错误的常见情况

Program terminated with signal 11, Segmentation fault.

空指针访问非虚函数

include <iostream>
class Foo
{
public:
  Foo() : a(0) {}
  void Bar() { std::cout << "Bar:" << a << std::endl; }
private:
  int a;
};
int main() {
  Foo* f = NULL;
  f->Bar();
  std::cout << "hello" << std::endl;
  return 0;
}

(gdb) bt
#0  0x00000000004008ef in Foo::Bar (this=0x0) at null.cpp:6
#1  0x00000000004008bb in main () at null.cpp:14
(gdb)

空指针访问虚函数

#include <iostream>
class Foo
{
public:
  Foo() : a(0) {}
  virtual void Bar() { std::cout << "Bar:" << a << std::endl; }
private:
  int a;
};

int main() {
  Foo* f = NULL;
  f->Bar();
  std::cout << "hello" << std::endl;
  return 0;
}

(gdb) bt
#0  0x0000000000400866 in main () at null.cpp:14
(gdb) p f
$1 = (Cannot access memory at address 0x0

野指针访问虚函数

#include <iostream>
class Foo
{
public:
  Foo() : a(0) {}
  virtual void Bar() { std::cout << "Bar:" << a << std::endl; }
private:
  int a;
};

int main() {
  Foo* f = new Foo();
  delete f;
  f->Bar();
  std::cout << "hello" << std::endl;
  return 0;
}
(gdb) bt
#0  0x00000000004009c4 in main () at null.cpp:15
(gdb) p f
$1 = (Foo *) 0x602010

原文链接: https://www.cnblogs.com/uhziel/p/cpp_segmentation_fault.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    C++中段错误的常见情况

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/200931

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月12日 下午8:36
下一篇 2023年2月12日 下午8:37

相关推荐