*** Error in `': free(): invalid next size (fast): 0x0000000000667890 *** - c++

This was a function that i made, it calculated Fibonacci Numbers, but when I run it i get the following error
Error in `': free(): invalid next size (fast): 0x0000000000667890
int fib(int n) {
int fibn=0;
std::vector<int> x{0,1};
for(int i = 2 ; i <= n ; i++)
{
x[i]=x[i-2]+x[i-1];
}
fibn=x[n];
return fibn;
}

std::vector<int> x{0,1};
You have a vector with two elements. Valid indices are 0 and 1.
for(int i = 2 ; i <= n ; i++)
{
x[i]=x[i-2]+x[i-1];
}
After the first iteration, you access x[2] and beyond which is outside the bounds of the vector. The behaviour of the program is undefined.
You don't need to store the series in a vector since you're only returning the last value. You only need to store the last two values.

Your vector x only has 2 elements, but your loop starts by setting i to 2 and then does x[i] (aka x[2]) on the first iteration, which is out of bounds since only the indices 0 and 1 are valid.
Remember that array indices start at 0 in C++.
Accessing out of bounds is Undefined Behaviour and as a result your entire program is invalid and the compiler is not required to generate anything sensible, nor is it obliged to tell you about your error.

Related

vector.size() is working unexpectedly in comparision

When I use vector.size() in comparisions it gives unexpected results
vector<int> v;
for(int i = 0; i < v.size() -1;++i){
printf("i = %d\n", i);
printf("v[i] = %d\n", v[i]);
}
since the size of vector is 0, it shoudn't print anything but, it enters for loop and prints i = 0 and give segmentation fault. But it shouldn't even enter the for loop as v.size() - 1 is -1.
Why is it happening?
The problem is your loop:
for(int i = 0; i < v.size() -1;++i)
More specifically, this part of the condition: v.size() - 1.
The size function returns a value of type size_type, which if you read e.g. this vector reference will see is an unsigned type.
That means when you subtract 1 from the value 0, you don't get -1 but instead get a very large value since unsigned underflow wraps around to its highest value.
That means your loop will indeed iterate, at least once, and lead to UB (Undefined Behavior) when you index out of bounds.
Vector size is an unsigned int, so v.size() - 1 will never be -1 but some very large integer.

Filling an array causes the stack around the array to be corrupted

I'm trying to fill a 4x6 array with random numbers between 0-25 using a for loop inside a for loop. A runtime error occurs after the array is generated- "Stack around the variable "grid" was corrupted. What is causing this to happen?
int grid[4][6];
for (int y = 0; y < 4; y++) {
for (int x = 0; x < 6; x++) {
grid[x][y] = (rand() % 25);
}
}
You're writing out of bounds. Your loop can write, for example, at (5, 3), which is outside the bounds of the array. In order to fix this, use x for the outer loop and y for the inner loop.
I think your indices are backwards, where you have x it should be y and vice versa
As the others have said, you've got the row and column indices backwards. The reason this is a problem is that in C and C++, the 2D array access:
grid[x][y]
is treated as the equivalent pointer expression:
*(grid + (x*COLS + y))
In this case, since C and C++ use row-major ordering, COLS is 6. Additionally, a 2D array is equivalent to a 1D array of size (ROWS * COLS), meaning that in this case you effectively can address elements 0 through 23 of that 1D array.
Now, looking at your loop structure, you can see that given the pointer arithmetic rule, you'll access element 24 (thus clobbering the stack) when x is 4 and y is 0--that is, *(grid + 4*6 + 0), or the 4th iteration of your inner loop.
Switch your loop order (0 <= x < 4 and 0 <= y < 6) and your problem will go away.
int grid[6][4];
You can use gdb, valgrind or anything else to find out the reason of segmentation fault.

Unexpected results when calling resize() on an STL vector in C++

In the following code, if I call v.resize(n), the program will print out 0 0 0 0 0 0 0 0 0 0, which is not what I wanted to see. However, if I comment the line containing v.resize(n) out, it will print out 0 1 2 3 4 5 6 7 8 9, which is what I wanted to see. Why is this the case? What's wrong with my logic here?
#include <iostream>
#include <vector>
using namespace std;
int main( int argc , char ** argv )
{
int n = 10;
vector<int> v;
v.resize(n);
for( int i=0 ; i<n ; i++ )
{
v.push_back(i);
}
for( int i=0 ; i<n ; i++ )
{
cout << v[i] << " ";
}
cout << endl;
return 0;
}
resize ensures the vector contains exactly n elements, while push_back appends items to the vector, so the nubmers are added after zeros that occupy the vector after resizing. You can see it if you print all the numbers in the vector (< v.size()) instead of just first n.
Method that behaves as you seem to have expected is reserve():
Effects: A directive that informs a vector of a planned change in size, so that it can manage the storage allocation accordingly. After reserve(), capacity() is greater or equal to the argument of reserve if reallocation happens; and equal to the previous value of
capacity() otherwise. Reallocation happens at this point if and only if the current capacity is less than the argument of reserve(). If an exception is thrown other than by the move constructor of a non-CopyInsertable type, there are no effects. (ยง23.3.6.3/2)
v.push_back(i) increases the size of the vector v by 1 with i being the value of the last element in that vector. That is why the 10 zeros are retained at the start (i.e. front) of the vector.
You should write v[i] = i instead.
Whatever you do, don't drop the line v.resize(n); and retain your push_back as it's suboptimal to piecewise resize a vector - due to memory reallocation. (Although a good stl will have optimisations for such programming it's good practice not to rely on that).
vector.resize()
Resizes the container so that it contains n elements.
You're resizing it to n (10). So now it has ten 0's in it. Then you add ten more numbers (0 to 9) to the end of the list (via push_back()). Finally, you print out only the first n (10) which are still all zero.
Your program is doing exactly what you're telling it to do.

C++ assigning values to index 10 of an array affects index 0

I have a 2 dimensional array that is filled with info and has 10 indexes. When I run the code below :
for(int studentIndex = 0; studentIndex < numOfStudents; studentIndex++)
{
if(grade[studentIndex][9] > 59){
grade[studentIndex][10] = 1; // 1 stands for pass
}else{
grade[studentIndex][10] = 0; // 0 stands for fail
}
}
grade[studentIndex][10] changes and so does the grade[studentIndex][0] for the next index. the problem is somewhere there because when I cout index 0 before this portion, the value is fine but after this it changes to 1 or 0.
In an array of size 10, the highest index is 9 since indexing begins at 0. I'm guessing that grade[index][10] is basically pushing the pointer forward into grade[index+1][0] and that's why you're seeing this behaviour. You'll need to either enlarge your student info array to 11 or figure out whether you're getting your indexing wrong.
and so does the grade[studentIndex][0] for the next index
This makes it sound like grade is defined as int grade[numOfStudents][10] (or something in that direction). The valid indices for the subarray are only 0 to 9.

Array index loop variable resets to zero in C, C++

I have declared an array of length N (suppose). Now, I assign some values to the elements of this array using a loop (the loop variable is used as the array's index). The code's as follows:
int main()
{
int arr[4], j;
for(j=0; j<10; j++)
{
printf("%d\n", j);
arr[j] = 0;
sleep(1);
printf("%d\n\n", j);
}
return 0;
}
I expected the output to be 0 1 2 .. 9. But what actually happened was that j got reset to 0 when the assignment arr[N+2]=0 (arr[6]=0, in this case) was executed in the loop.
What's actually happening here? Am I missing something?
Your array has 4 elements and your index is out of range so you are just stomping on memory.
Given the code here, I'd expect arr[4] to reset the array, but since you mentioned that it's of length N and N+2 is what causes it, there might be some padding in your stack. In any case, when you declare the array and j, they are put on the stack. In your case, j is in a position such that when your index is out of bounds you are accessing the memory where j is.
the behaviour of the code is undefined as it has a bug. arr has a size of 4 but you are indexing past this size with j
Your array is overflowing. You defined it like this with 4 elements:
int arr[4]
But you're trying to assign 10 elements.
j is apparently located immediately after the array, so when you assign arr[6] = 0, you're clearing j.