通过指向结构的指针访问结构成员时,Valgrind 抱怨读取无效

Valgrind complains of invalid read when accessing struct member through pointer to struct

结构定义如下:

struct section_{
    int start;
    ...
};

出于我不会深入探讨的原因,我需要将指向结构的指针传递给接受 void* 的函数。该函数如下所示:

void* my_fun(void* sec){
    section_* section = (section_*)sec;
    int start = section->start; // <---- valgrind complains here
    ...
}

我有一个 std::vector<section_*>,我需要对该向量的每个元素调用 my_fun。我是这样做的:

std::vector<section_*> sections = get_sections();
for (int i = 0; i < sections.size(); ++i){
    my_fun((void*)sections[i]);
}

get_sections() 函数类似于:

std::vector<section_*> get_sections(){
    std::vector<section_*> sections;
    section_ sec1;
    sec1.start = 0;
    ...
    sections.push_back(&sec1);
    return sections;
}

我已将问题追踪到 my_fun 中的行

int start = section->start;

错误说:

==3512== Invalid read of size 4
==3512==    at 0x41A970: my_fun(void*)
...
==3512==  Address 0xffeffa2a0 is on thread 1's stack
==3512==  14160 bytes below stack pointer

即使读取无效,我仍然能够访问 my_fun 中的结构成员,并且它们是正确的值。这是为什么?

我知道这段代码是零散的,但实际代码比我展示的要复杂和冗长得多,尽管我认为我展示了所有相关部分。希望我提供的信息足够了。

如@BoPersson 的评论中所述,您向向量添加了一个局部变量:

std::vector<section_*> get_sections(){
    std::vector<section_*> sections;
    section_ sec1;    // <- Local, temporary variable 
    sec1.start = 0;
    ...
    sections.push_back(&sec1); // <- Address of local var
    return sections;
    // When this function ends, sec1 is no longer valid
}

您可以使用 new 创建 sec1delete 稍后创建)。或将矢量类型更改为 std::vector<section_> sections;.