惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Engineering at Meta
Engineering at Meta
博客园_首页
J
Java Code Geeks
Jina AI
Jina AI
B
Blog RSS Feed
量子位
有赞技术团队
有赞技术团队
M
MIT News - Artificial intelligence
L
LangChain Blog
Microsoft Security Blog
Microsoft Security Blog
小众软件
小众软件
博客园 - 聂微东
月光博客
月光博客
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
博客园 - 三生石上(FineUI控件)
Last Week in AI
Last Week in AI
MongoDB | Blog
MongoDB | Blog
I
InfoQ
罗磊的独立博客
H
Hackread – Cybersecurity News, Data Breaches, AI and More
爱范儿
爱范儿
Y
Y Combinator Blog
Vercel News
Vercel News
雷峰网
雷峰网

博客园 - 程鑫

Harness Engineering 介绍与最佳实践 Thriving in a Crowded and Changing World: C++ 2006–2020 读后总结 C++20中对于并发方面的进步 ClickHouse性能调优 - 当磁盘IO是瓶颈的时候 手撸一个C++迭代器 ClickHouse的向量处理能力 STL库的ranges ClickHouse中的各种设置 OLAP与数据仓库和数据湖 mmap访问内存方式 关于ClickHouse的一些小技巧 ClickHouse中“大列”造成的JOIN的内存超限问题 ClickHouse的JOIN算法选择逻辑以及auto选项 ClickHouse的Join算法 一种高效且节约内存的聚合数据结构的实现 “过早优化是万恶之源”这句话的源头 ClickHouse的WITH-ALIAS是如何实现的 如何与chatgpt共存 多线程与同步 C++编译器选择是否自动生成代码的背后逻辑
`static_cast` caution
程鑫 · 2024-03-17 · via 博客园 - 程鑫

static_cast caution

It is likely to lead unexpected behavior and maybe dangerous to invoke static_cast on wrong C++ object. Below example demostrates it.

On the second invocation of foo, foo(d2), the instance of class D2 is casted into instance of class D1 and the memory address for access to member variable b of D1 is calculated as d2's address + offset of b. The resulted address is actually out of the available memory of instance d2 because d2 is instance of class D2 which is smaller than class D1(D1 has a big member variable arr). That causeses unexpected behavior: if the memory which the address points is already allocated to the current process, the wrong data(the memory is occupied by another objects or values) are read; otherwise a "memory access violation" exception occurs.

#include <iostream>
#include <array>

using namespace std;

class Base
{
public:
    virtual void say()
    {
        cout << "hello, base;" << endl;
    }
};

class D1 : public Base
{
public:
    char a = '*';
    std::array<char, 10000> arr{};
    char b = '+';

public:
    void say() override
    {
        cout << "hello, D1;" << a << endl;
    }

    void jump()
    {
        cout << "jump " << b << endl;
    }
};

class D2 : public Base
{
public:
    long long v = 7777;

public:
    void say() override
    {
        cout << "hello, D2;" << v << endl;
    }
};

void foo(Base & bb);

int main()
{
    D1 d1;
    D2 d2;
    foo(d1);
    foo(d2); // cause memory access violation!!!
}

void foo(Base& bb)
{
    D1& d = static_cast<D1&>(bb);
    d.jump();
}

In my experiment, the "memory access violation" exception happens.
image