Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
406 views
in Technique[技术] by (71.8m points)

c++ - Check if a pointer points to allocated memory on the heap

I want to know if a pointer points to a piece of memory allocated with malloc/new. I realize that the answer for an arbitrary address is "No you can't" but I do think it is possible to override malloc/free and keep track of allocated memory ranges.

Do you know a memory management library providing this specific tool?
Do you know something for production code?

Valgrind is great, but it is too much instrumentation (slow) and as Will said we don't want to use Valgrind like this (making the soft crash is good enough).
Mudflap is a very good solution, but dedicated to GCC, and sadly, a check does not simply return a boolean (see my answer below).
Note that checking that memory writes are legal is a security issue. So looking for performance is motivated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

A proof it probably cannot be usefully done:

char * p1 = malloc(1);
free( p1 );
char * p2 = malloc(1);   // probably allocates same block as first malloc

Now both p1 and p2 point at same memory on heap, but only p2 is valid.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...