|
From: mathog <ma...@ca...> - 2014-04-24 18:54:11
|
Is there some trick to get valgrind to detect this sort of dangling
pointer error?
cat >test.cpp <<EOD
#include <iostream>
int sub(void) {
int *p;
{
int x = 123;
p = &x;
}
std::cout << "value of p " << *p << std::endl;
return *p;
}
int main() {
int ret = sub();
std::cout << "value of ret " << ret << std::endl;
return ret;
}
EOD
g++ -Wall -g -O0 -o test test.cpp
./test
value of p 123
value of ret 123
valgrind ./test
# no problems reported
If sub() instead uses an explicit
p = (int *) malloc(sizeof(int));
*p = 123;
free(p);
then valgrind sees the use of memory after free. But in the original it
seems that x is on the stack,
and there is never an explicit delete() when the variable goes out of
scope, so nothing tells valgrind
that that memory is no longer valid.
(This came up on the Inkscape developer list, originally in reference to
the warnings clang emits.)
Thanks,
David Mathog
ma...@ca...
Manager, Sequence Analysis Facility, Biology Division, Caltech
|
|
From: <jr...@bi...> - 2014-04-25 03:58:44
|
int sub(void) {
int *p;
{
int x = 123; p = &x;
}
// Although x is out-of-scope according to the language,
// gcc/g++ allocates local variables by subroutine, not by block contour.
// (Allocating by subroutine is faster and smaller.)
// Therefore p still points somewhere into the current frame,
// and memcheck does not complain when de-referencing p.
// In order to elicit a complaint from memcheck, then the compiler
// must allocate and de-allocate by block contour.
return *p;
}
|