Post

Bug分享:栈上的临时变量赋值给class的引用型成员

最近遇到一个开源库中的bug,简化后的示例代码如下:

  • 类成员变量mValue是个引用
  • 函数doTask中创建一个Demo对象,其中mValue指向栈上的临时变量a
  • 创建的Demo对象交给另一个线程使用,另一个线程操作Demo对象的时候,因为函数doTask已返回,栈上的临时变量a已失效,导致踩内存
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include <string.h>

#include <chrono>
#include <thread>

class Demo {
public:
    Demo(int& value) : mValue(value) {
    }

    int& mValue;
};

void doTask() {
    int a = 1;
    printf("Address range of a:%p\n", &a);

    auto ptr = std::make_shared<Demo>(a);
    std::thread workThread([ptr]() {
        std::this_thread::sleep_for(std::chrono::seconds(1));
        // 栈内存被踩:doTask函数已结束,ptr->mValue指向的变量a已失效
        ptr->mValue = 2;
    });

    workThread.detach();
}

void myValueChange() {
    char b[1024];
    memset(b, 0, sizeof(b));
    printf("Address range of b:[%p, %p)\n", b, b + sizeof(b));

    std::this_thread::sleep_for(std::chrono::seconds(2));

    // 数组b的内存被踩
    for (uint32_t i = 0; i < sizeof(b); i++) {
        if (b[i] != 0) {
            printf("value of b[%d] is change to %d\n", i, b[i]);
        }
    }
}

int main() {
    doTask();
    myValueChange();
    return 0;
}

直接编译运行上面的代码,可以看到函数myValueChange中数组b的内存被修改了,躺着中枪:

1
2
3
Address range of a:0x7ffdc0cc37c0
Address range of b:[0x7ffdc0cc33e0, 0x7ffdc0cc37e0)
value of b[992] is change to 2

实际工程中,这种偶现的踩内存问题比较难排查,因为罪魁祸首是A线程,但是最终程序可能crash在B线程,犯罪现场已被破坏。上面的demo,在我的Ubuntu 20.04.4 LTS上能逃过-fstack-protectorAsan的法眼,Android平台开启HWASan倒是可以检测出来。

This post is licensed under CC BY 4.0 by the author.

© coderhuo. Some rights reserved.

本站总访问量次,本文总阅读量

Using the Chirpy theme for Jekyll.