How can I intentionally initialize a variable with uninitialized data so that valgrind will treat the variable as uninitialized?

StackOverflow https://stackoverflow.com/questions/21752416

  •  11-10-2022
  •  | 
  •  

Question

I have a trash data buffer in my code which I pass to a function which writes to it. I do not need the data of this trash buffer. Since I need such trash data buffers in multiple places, but never read from them, I use the same trash buffer everywhere.

When some bogus code reads from the trash data buffer this would be fatal, or, for example, when I use a trash data buffer where I should have used a proper dedicated buffer instead.

Ideally I would like to make bogus code fall over quickly, so I scramble the data after calling the writing function, so nobody can use (and rely on) the trash data.

Now I had the idea that I could copy uninitialzed data over the trash data instead of scrambling it, so valgrind could find all reads from the trash buffer.

My current solution is to new[] some bytes and copy the uninitialized content over the trash buffer and then delete[] the uninitialized data. Since the uninitialized data is 0 most of the time (unfortunately) I XOR it with a pattern. This all seems quite complicated for such a simple thing.

Did anyone come up with a better solution?

Was it helpful?

Solution

Valgrind (and memcheck) have a C API!

You can simply do this:

#include <memcheck.h>

// ....

VALGRIND_MAKE_MEM_UNDEFINED(trash_buffer, trash_length);

You could also use VALGRIND_MAKE_MEM_NOACCESS if you want valgrind to consider the data to be inaccessible instead of just unitialized.

This will have very little runtime overhead when running outside of valgrind. Your approach of copying stuff around could be expensive, even when not running inside valgrind.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top