[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: valarray help
From: |
Rolf Magnus |
Subject: |
Re: valarray help |
Date: |
Fri, 08 Apr 2005 11:23:18 +0200 |
Mephistopheles Jones wrote:
> I'm having trouble when using a valarray as a class member. I compile
> with g++, and my gcc is version 3.3.5. Here's a highly simplified
> example:
>
> struct ValWrapper {
> valarray<int> item;
> };
>
> int main() {
> ValWrapper v;
Here, v.item gets default initialized to a valarray with size 0.
> v.item=valarray<int>(-1,10);
Here, you assign a valarray with a different size to v.item, which results
in undefined behavior. Both valarrays in an assignment need to be of the
same size.
> v.item[1]=23; // <--- segfault here
> return 0;
> }
>
> The assignment in the penultimate line of main gives a segfault. However,
> when I do this
>
> int main() {
> valarray<int> v(-1,10);
This creates v as a valarray of size 10. No undefined behavior here.
> v[1]=23;
> return 0;
> }
>
> all works fine. Replacing all instances of "valarray" with "vector" above
> gives an error as well, but curiously the errors are different. I get
> "Segmentation fault (core dumped)" for valarrays and "Aborted (core
> dumped)" for vectors.
Are you really just replacing "valarray" with "vector"? No other change? So
you have:
v.item=vector<int>(-1,10);
? Then it's not surprising. For some reason, the parameters of the valarray
constructor are reversed compared to other containers. So you're trying to
create a vector of size -1 with each entry having a value of 10. The -1
gets converted to an unsigned value of std::vector<int>::size_type, which
results in a very big value. Your system probably can't allocate such a big
amount of memory, and so a bad_alloc exception is thrown, which you don't
catch, so std::unexpected is called, which in turn calls std::terminate,
which calls std::abort. Therefore, your program gets aborted.
> I believe my assignments are syntactically correct.
Syntactically, yes.
> Any pointers?
No, pointers are not needed ;-)
- valarray help, Mephistopheles Jones, 2005/04/07
- Re: valarray help,
Rolf Magnus <=