Using deque<double> as array

Hi,

I am having trouble with the following code

1
2
3
4
5
6
7
8
9
10
11
size_t l = 100;
std::deque<double> numbers(l, 0.0);
for(size_t j=0;j<l;j++) {
  numbers[j] = j;
}
long double mean = 0;
double* data = &numbers[0];
for(size_t i=0;i<l;i++) {
  mean += (data[i] - mean) / (i + 1);
}
printf("Mean == %Lf\n",mean);

(the reason for the data pointer is that originally I wanted to use functions from gsl which require plain arrays and there I got the error. So I rebuild it for debugging)

My problem is now that Valgrind reports an "invalid read of size 8" in line 9 as soon as i is larger than 64. The reason for the error is "Address 0xf167b90 is 0 bytes after a block of size 512 alloc'd". These values (64, 512) do not depend on the actual size of numbers.The line that allocated the memory is line 2.

Am I doing something wrong, or is this a bug in Valgrind?
I am especially confused because the first loop does not give any error and my understanding is that deques are stored as a contiguous block of memory, so there should be the same memory accessed, no matter if I use numbers[j] or data[j].

Thanks,
FReAK
Last edited on
my understanding is that deques are stored as a contiguous block of memory

And there you err.
With a vector you would be right.
Which raises the question: why are you replacing arrays by deques? I think vectors are the "standard" C++ replacements of arrays. Even with vectors, be careful when using direct pointers: any function that changes the size of a vector can invalidate all pointers!

[On that note: why does everyone keep suggestion vectors, while valarrays seem to do the exact same if you're using a fixed size?]
Thanx for your answers!

After checking the deque reference again, I see
On the drawback side, unlike vectors, deques are not guaranteed to have all its elements in contiguous storage locations, eliminating thus the possibility of safe access through pointer arithmetics.

Me stupid ...

@Gaminic deques were in my programm at first place because I modify the stored values at the beginning and at the end (so ther is no fixed size and deque should perform better than a vector). The need to convert this container to an arrays comes from gsl which I wanted to use for statistics generation from the stored values.
Topic archived. No new replies allowed.