why this program is crashing - c++

I wrote a small program in which, I want to set the value of a frame to 255 based on a vector:
result = cv::Mat::zeros(frame.size(),CV_8UC1);
std::vector<cv::Point2f> imageCorners;
.......................................................
for ( int i = 0 ; imageCorners.size();i++){
std::cout << imageCorners[i]<< std::endl;
result.at<uchar>(imageCorners[i]) = 255;
cv::imshow("result",result);
}
my question is: why the program crashes just after finishing the loop ?? even I see that result is correct ? the error message that I get is :
vector subscript out of range

for ( int i = 0 ; imageCorners.size();i++){
// ^^^^^^^^^^^^^^^^^^^
The underlined part is the condition. In this case you are saying "keep looping until the size of imageCorners is "false" (i.e. 0)". But you never change the size of the vector, so this condition never stops the loop, i keeps getting bigger, until you try to access an index that isn't actually in imageCorners.
Presumably you mean to loop until i gets bigger than the vector. Then use
for (int i=0; i < imageCorners.size(); ++i) {

This looks dodgy to me:
for ( int i = 0 ; imageCorners.size();i++){
you surely wanted to write something like:
for ( int i = 0 ; i < imageCorners.size();i++){

The condition of your loop, imageCorners.size() only yields the number of elements stored in the container. The statement will always evaluate to true as soon as you put one element into imageCorners. What you want is i < imageCorners.size().

for ( int i = 0 ; imageCorners.size();i++)
I think this loop will run forever if imageCorners.size() is different than 0. So when this
std::cout << imageCorners[i]<< std::endl;
gets executed, at some point i will be out of bounds and the program will crash.

Related

Random Symbols Getting Printed Without Initialization

I made a fairly short text-based animation program:
#include <iostream>
void animation(char words[], int sizeOfWords) {
for(int x = 0; x < sizeOfWords; x++){
for(double y = 0; y < 10000000; y++);
std::cout << words[x];
if(words[x] == '!') std::cout << std::endl;
}
}
int main() {
char words[] = {'H','e','l','l','o',' ','W','o','r','l','d','!','T','h','i','s',' ','i','s',' ','m','y',' ','f','i','r','s','t',' ','C','+','+',' ','a','n','i','m','a','t','i','o','n','!','H','o','p','e',' ','y','o','u',' ','e','n','j','o','y','e','d','!'};
int amountOfLetters = 0;
for(unsigned x : words) amountOfLetters++;
animation(words, amountOfLetters);
}
When I first made the program I forgot to initialize int amountOfLetters; to 0. That is when I got all these random symbols. The program is fine with or without initializing it. Just without assigning 0 to it, I get these extras in the end.
Without Initialisation Of The Variable will give the following result:
Hello World!
This is my first C++ animation!
Hope you enjoyed!
!
t ht ÉH P j     T j ­Ðou2ö¤.■   Á╬ouÈ╬ouht mzou
Process returned 0 (0x0) execution time : 11.466 s
Press any key to continue.
With Initialisation Of The Variable will give the following result:
Hello World!
This is my first C++ animation!
Hope you enjoyed!
Process returned 0 (0x0) execution time : 4.444 s
Press any key to continue.
You could try running the codes yourself if you want. I would just like to know why are these symbols being printed out. If you can help i'd appreciate it. If not thanks for stopping by.
This post isn't a duplicate of Why uninitialized char array is filled with random symbols?. I talk about passing the number of elements in an array and passing them as argument, afterwards looping through them. The other post is simply just talking about initializing an array Without Information in it and printing it. Meanwhile, again, I am talking about Having Information, just the size of the array holding them was the problem. Simply theirs is about printing an array with no elements, mine is about looping through an array with elements but, mistakenly making an error for the size.
Your animation function is accessing the char array by index, until the index == sizeOfWords. If amountOfLetters is not initialised you will start incrementing a random value, and will therefore read past the end of the array in animation. That, of course, has random values.
When I first made the program I forgot to initialize int amountOfLetters; to 0. That is when I got all these random symbols. The program is fine with or without initializing it. Just without assigning 0 to it, I get these extras in the end.
That's because without initializing amountOfLetters the amountOfLetters++; operation is undefined behavior.
amountOfLetters may have an arbitrary value at the beginning of the loop, as it was left on the stack from previous operations.
Also note that you could greatly simplify and improve your code just omitting the loop and write:
animation(words, sizeof(words));

C++ Function will not execute more than once

I've tried looking around but I can't find anything about this anywhere.
I'm writing a custom array class with a "push" function to add a value to the array.
It seems to work perfectly fine but won't execute more than once.
Take the main method below for example:
int main()
{
Array<int> test(4,5);
test.push(4);
test.writeOrdered("Output.txt");
return 0;
}
This will put the int value 4 into the array at the first available position and execute the writeOrdered function.
The following main method, on the other hand:
int main()
{
Array<int> test(4,5);
test.push(4);
test.push(5);
test.writeOrdered("Output.txt");
return 0;
}
This will put the number 4 into the array at the first available point as above and then stop. It won't execute any further lines of code.
Here's the push function for reference:
void push(Datatype p_item)
{
bool inserted = false;
int i = 0;
while (inserted == false)
{
if (m_array[i] < 0)
{
m_array[i] = p_item;
i++;
inserted = true;
cout << p_item << " saved to array" << endl;
system("pause");
}
}
}
You have an infinite loop. After the first insert m_array[0] >= 0 and i never grows. You would have found it out, had you debugged the code somehow.
Basically I don't understand your push function but the way it is, after you insert a non-negative value into the first position any further call to your push function results in a tight loop.
I imagine that you want the i++ outside the if statement.
Without seeing the full implementation of the Array class I would guess that the array m_array contains negative numbers by default. This will allow the first call to the push method to succeed. The next call to the method contains a value of 4 at index 0 and will be stuck in an infinite loop because inserted will never be set to true nor will the value of i be incremented.

My while loop exits prematurely

thanks for reading this.
I am writing a code to read a big data file. And I try to use a while loop to read it one piece at a time.
But when I write
while(TimeStep++)
it will exit at the first loop.
if I write,
while(TimeStep+=1)
it will be just fine.
Also, if I initialize
int TimeStep=-1;
it will exit at the first loop. But if I initialize
int TimeStep=0;
it will be fine. The magic of while() confuse me. Please help me understand while loop.
Here is all my code.
//get diffusion of all the particles in the 256Coordinate.txt file and diffusion of a single particle.
using namespace std;
typedef vector<double> vec;
int ReadStructure(vec & Coordinate,int size,ifstream & TrajectoryFile){
double a;
for(int i=0;i<size*3;i++){
if(!(TrajectoryFile.eof())){
TrajectoryFile>>a;
Coordinate[i]=a;
}
}
//cout<<Coordinate[1]<<endl;
if(TrajectoryFile.eof()){
return 1;
} else {
return 0;
}
}
int main(){
int ContinueFlag=0,i,j,k;
double a,b,c;
vec Coordinate;
string filename= ("../256Coordinate.txt"); // a file that contains 256*5000*3 numbers
int size=256;
Coordinate.resize(size*3);
int TimeStep=0;
ifstream TrajectoryFile(filename.c_str());//open the .txt file and begin the read data
//TrajectoryFile>>a;
//cout<<a<<endl;
while(TimeStep+=1){//keep looping untils breaks.
ContinueFlag=ReadStructure(Coordinate,size,TrajectoryFile);//read the .txt file and store the values in the vector Coordinate[3*256]. Read 3
*256 numbers at a time.
// cout<<"ContinueFlag= "<<ContinueFlag<<endl;
if(ContinueFlag==1) break;//if we reach the end of the file, exit.
// cout<<Coordinate[1]<<endl;
}
cout<<"total number of timesteps= "<<TimeStep-1<<endl;
}
the body of while loop will execute when the loop condition under
while(loop condition)
is true.
So if you set TimeStep =0 to start with. It will test whether TimeStep ==0 before executing the while loop. Any non-zero value is treated as True. If it is 0, loop body will not execute.
If you initialize as int TimeStep=-1;, TimeStep+=1 will set TimeStep =0, which is equivalent to false, so loop body will not execute.
If you do not know the loop termination condition beforehand, simply use
while (true)
is better than using such a TimeStep variable.
Try:
while(true){
ContinueFlag=ReadStructure(Coordinate,size,TrajectoryFile);
if(ContinueFlag==1)
break;
}
In C++ the integer value 0 is False, any other value including negative integer is True. While loop exits when false.
I think your main problem is not understanding the while loop, it's understanding the increment operator ++.
Let's work with an example:
int x = 5;
int y = x++;
Here, x will have a value of 6 (because you made ++), but which value will y have? Actually, it will be 5. This is a so-called 'postincrement' operator: see, you assign first, and increment later.
If you wrote this
int x = 5;
int y = (x += 1);
Then you would have x = 6 as before, but this time y = 6 also, so you first increment x and only then assign it to y.
This should make your while loop misunderstanding go away:
int TimeStep = 0;
while(TimeStep++)
Here, TimeStep will get the value of 1, but only after it was used by while to test for exit, but while will see the old value (as y in the example above), and the old value is 0, so while exits immediately.
int TimeStep = 0;
while(TimeStep+=1)
In this case the loop goes on because you first increment the TimeStep and then let while test if it's nonzero.
I would really suggest you write a simple loop, why are you testing if TimeStep is nonzero anyway? Just do it like this:
while(true) { // Infinite cycle, until brake is encountered
TimeStep++;
}
The while loop expects a true/false value, according to that, TimeStep++ if TimeStep = -1 is false, because TimeStep++add 1 to TimeStep , so == 0, if TimeStep = 0and you add 1 then is ALWAYS true, because true is every value != 0...
I think you may need to get a better understanding of boolean algebra.
Here's a link to a tutorial http://www.electronics-tutorials.ws/boolean/bool_7.html.
A while loop is based around a boolean expression. If the expression within the while loop parentheses is true it will enter the loop and stop until that expression evaluates to false.
It works when the integer that you are using is set to 0 or 1 because 0 represents false and 1 represents true. You can't use an integer as a boolean expression if it is not 0 or 1.
It looks like you want the loop to break when ContinueFlag==1. So just use that as the while loop parameter. An alternative way would be to just change that code to while (true).
Since you want ContinueFlag to be set at least once (so you know when to break) I would suggest using a do while loop which executes at least once and then repeats if the expression is true.
USE THIS:
do {
ContinueFlag=ReadStructure(Coordinate,size,TrajectoryFile);
TimeStep++; //This allows for TimeStep to increment
} while (ContinueFlag!=1); //It will loop while ContinueFlag!=1 which will cause
//the loop to end when ContinueFlag==1
This is a better way of writing your code (as opposed to while (true)). This allows you to easily see what the purpose of the loop is.

For loop adding to a variable

I am trying to create a loop that adds 1 to a int variable every time the if statement is true
But while testing the code even though the if statement is true the variable is not incremented, as if the my for loop is not incremented at all....
Code sample:
int left_jab_count;
if(area >=100000 && area1 <100000)
{
cout<<"LEFT JAB HAS BEEN THROWN"" "<<area<<endl;
for(int left_jab_count = 0; left_jab_count < 0 ;++left_jab_count)
{
cout<<"Left Jab :"<<left_jab_count<<endl;
}
}
can anybody see where am going wrong here ?
for(int left_jab_count = 0; left_jab_count < 0 ;++left_jab_count)
//^^^^left_jab_count is never < 0
// change <0 to some value larger than 0
you for loop is never executed. Therefore, left_jab_count will never get incremented, you never enter the body of for loop.
Meanwhile, you declared left_jab_count twice.
tacp has adequately covered the issues with your current code, so I won't go into those. Based on your specification, "I am trying to create a loop that adds 1 to a int variable every time the if statement is true", what you want is something like this:
int left_jab_count = 0; // Don't forget to initialise this
while (true) // Replace with real loop
{
// Do NOT initialise left_jab_count here, otherwise it will be
// reset to 0 on every loop
// Insert code which changes area and area1
if (area >= 100000 && area1 < 100000)
{
cout << "LEFT JAB HAS BEEN THROWN " << area << endl;
left_jab_count++;
}
}
Unless you've misstated your specification, then you don't need a for loop inside the if block.
JBentley answered the question which was set by you. In the While statement that he posted you should add a condition which is true so that the code inside can run. I guess you want to enter:
while (left_jab_count < NUMBER)
Be sure to have a true condition so that the loop can start and run the if statement.

in visual c++, warning comes but program doesnt runs furthers, is there any way to igonre it?

I have written some code, here is a snippet of it is:
int num[8],n=0;
for (n = 0; n<8; n++)
{
char temp = binnum[n];
num[n] = atoi(&temp);
cout << num[n];
}
It doesn't gives any error, but I do get a warning. When I run it on C++, it gives Run Time Check Failure - The variable n is being used without being initialized.
After that, it doesn't run any further and the program closes. Is there any way to ignore this error? Because if I initialize n, it gives the wrong answer. For example, if answer is 101011, it will give 10101100, which is wrong.
Initialize n as #anthares pointed out and increment it at the end of the loop so your loop actually works.
int number[8];
int n = 0;
do
{
char temp = binnum[n];
number[n] = atoi(&temp);
cout << number[n];
n++;
} while (n<8);
Your main problem (after all the edits) is that atoi takes a null-terminated char array (C-style string). The address of a single char variable does not make a C-style string.
To convert a single character in range ['0'...'9'] to a corresponding number use:
number[i] = temp - '0';
possibly having checked that temp contains a digit character.
Give a value to your vairable n before using it int number [8], n=0 for example. Otherwise, it is "not defined behavior" what is the value of n and how many iterations you will do in your cycle.
Also, As it is written your loop will go forever since you never change the value of n ...
You are using n before it is assigned a value. You need to ensure that n is initialized (to 0, maybe) before you begin to reference it in your code. You do not want to ignore this error.
Try something like this:
const int count = 8;
int number[count];
for (int i=0; i < count; i++)
{
char temp = binnum[i];
number[i] = atoi(&temp);
cout << number[i];
}
what? you never assign any value to n.
and even if you will for example do int number[8],n=0; you never change n's value you you will end up with an infinite loop.
You should really initialize n (and also increment it, for that matter).
You are probably running a debug build of your application. In this case, the variable is probably always initialized with the same value. This is why you see the result you expect. It seems to behave correct purely by accident.
As soon as your application is built in release mode, n may have a different value each time the program is run and thus the output will be unpredictable.
This is what happens when you have undefined behavior in your program.