Fix initialization (under Valgrind) in SparseArray::resize().
If SparseArray::resize() is called when sparse_to_dense_ is NULL (which
happens if it was initialized with the default constructor, then
resized) the Valgrind-only initialization code is not run and Valgrind
will complain about uninitialized memory accesses within the newly
allocated array.
This patch moves the init code out of the if (sparse_to_dense_) block
which is safe because in this NULL case max_size_ will be 0 and this
will be equivalent to the init code in the non-default constructor.
Change-Id: Ic0b86ddb692a525630370118c08e8e8feb812cca
Reviewed-on: https://code-review.googlesource.com/3870
Reviewed-by: Paul Wankadia <junyer@google.com>
diff --git a/util/sparse_array.h b/util/sparse_array.h
index d1e98f5..8f71fa0 100644
--- a/util/sparse_array.h
+++ b/util/sparse_array.h
@@ -279,16 +279,22 @@
int* a = new int[new_max_size];
if (sparse_to_dense_) {
memmove(a, sparse_to_dense_, max_size_*sizeof a[0]);
- // Don't need to zero the memory but appease Valgrind.
- if (InitMemory()) {
- for (int i = max_size_; i < new_max_size; i++)
- a[i] = 0xababababU;
- }
delete[] sparse_to_dense_;
}
sparse_to_dense_ = a;
dense_.resize(new_max_size);
+
+ // These don't need to be initialized for correctness,
+ // but Valgrind will warn about use of uninitialized memory,
+ // so initialize the new memory when compiling debug binaries.
+ // Initialize it to garbage to detect bugs in the future.
+ if (InitMemory()) {
+ for (int i = max_size_; i < new_max_size; i++) {
+ sparse_to_dense_[i] = 0xababababU;
+ dense_[i].index_ = 0xababababU;
+ }
+ }
}
max_size_ = new_max_size;
if (size_ > max_size_)