0

I don't understand what I'm doing wrong. My code should just increment i: 0.1 from zero, and add 0.5 to each position, really simple, but instead I get segmentation fault (core dumped).

Can someone give me hand?

vector<float> sinal;

int main(){
  sinal[0] = 0;
  for (float i = 0.1; i <= 1; i += 0.1){
    sinal[i] = sinal[i - 1] + 0.5;
    if (i == 1){
      break;
    }
    cout << "\n" << sinal[i];
  }

getchar();
cin.get();
}
 
  • 3
    Two things - `vector sinal;` is an empty vector of size 0 so any index into it is invalid (and results in UB). Using floating point values for array indexes is unusual and asking for trouble see https://stackoverflow.com/questions/588004/is-floating-point-math-broken – Richard Critten Apr 30 '21 at 14:52
  • Maybe you want to use `std::map` instead. Although that comes with its own traps. – François Andrieux Apr 30 '21 at 14:53
  • 2
    Since you are incrementing by `0.1`, there is no guarantee your loop will iterate the number of times you think it will, since `0.1` is an approximation. If you want to loop 10 times, then rewrite the loop using integer indexing, i.e. `for (int i = 1; i <= 10; ++i)`, and inside the loop, scale the integer back to a floating point by dividing by 10. [Here is one resource explaining this issue](https://wiki.sei.cmu.edu/confluence/display/c/FLP30-C.+Do+not+use+floating-point+variables+as+loop+counters) – PaulMcKenzie Apr 30 '21 at 14:55

2 Answers2

1

Two problems here:

1. When you access sinal[0] and sinal[i], sinal does not have any capacity yet.

2. Using a floating point number as a subscript is unusual, and could make errors happen. The subscript is normally the offset of the item you want to access, so if I want to access the fifth element, I use a subscript of 4, because I move forward 4 spaces to get to the fifth element. If I do 1.5 as a subscript, then I am trying to move forward 1 and 1/2 spaces, and our std::vector does not understand that. I am guessing that the overload of operator[] for vector takes only an int, so some kind of cast happens when you put a float.

For a solution, take a look at my other answer here: Not getting output in case of string.

"Core Dumped" is often trying to dereference a null pointer, or, in this case, trying to access an out of range object.

-1

The problem is the precision of floating point numbers, as well use of floating point numbers as indexes.

vector<float> sinal {0};

int main()
{
    for (int idx = 1; idx <= 10; idx++)
    {
        auto last = sinal.back(); // reference to last element in vector
        sinal[idx] = last + 0.5;
        if (i < 10)
        {
            cout << "\n" << sinal[idx]; 
            // cout << "\n" << sinal.back(); // Even better 
        }

    }
    //... more code...
}

the operator[] function expected a 'size_type' value; so it's very strange to use a floating-point type as the index.

thelizardking34
  • 338
  • 1
  • 12