C++类指针未初始化导致访问成员变量时报段错误

# 安装gcc和g++
yum install gcc
yum install gcc-c++.x86_64
// a.cpp

#include <iostream>
#include <unistd.h>

using namespace std;

class Test {
public:
    void test1() {
    }

    void test2() {
        age = 10;
    }

private:
    int age;
};

int main() {
    Test* test;
    test->test1();
    sleep(20);
    test->test2();
}
# -g加入调试信息
g++ a.cpp -g -o a

一个窗口在./a,另一个窗口gdb调试。

C++编译时确定成员函数地址,未初始化的类指针调用成员函数时直接通过函数地址调用,访问成员变量会报段错误。
除此之外,C++段错误可能原因有访问只读或者不存在的内存地址和数组越界。

posted on 2024-01-28 10:04  王景迁  阅读(20)  评论(0编辑  收藏  举报

导航