The struct is defined as such:
struct section_{
int start;
...
};
For reasons I will not go into, I need to pass a pointer to the struct to a function that accepts a void*
. The function looks like this:
void* my_fun(void* sec){
section_* section = (section_*)sec;
int start = section->start; // <---- valgrind complains here
...
}
I have a std::vector<section_*>
and I need to call my_fun
on each of the elements of this vector. I do this like so:
std::vector<section_*> sections = get_sections();
for (int i = 0; i < sections.size(); ++i){
my_fun((void*)sections[i]);
}
The get_sections()
function looks something like:
std::vector<section_*> get_sections(){
std::vector<section_*> sections;
section_ sec1;
sec1.start = 0;
...
sections.push_back(&sec1);
return sections;
}
I've tracked the problem down to the line in my_fun
that says
int start = section->start;
The error says:
==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
Even though I'm getting an invalid read, I am still able to access the members of the struct inside my_fun
and they are the correct values. Why is that?
I realize that this code is in little bits and pieces, but the actual code is much more complex and lengthy than what I'm showing, though I think I'm showing all the relevant parts. I hope the info I gave is enough.