-
Wheres the error?
Code:
#include<iostream>
#include<string>
#include<vector>
using namespace std;
int main()
{
vector<string> strNames(3);
for( int i = 0; i < 4; i++ )
cin >> strNames[i];
cout << endl << endl;
for( i = 0; i < 3; i++ )
cout << strNames[i] << endl;
return 0;
}
my job is to create a lesson on debugging, and so i thought a simple out of bounds error would work....but this compiles and runs with no fatal errors! I even changed the one for loop from 4 to 5 and it didn't even change the way the program executed, ie it still only asked for 4 names? I'm losing my mind here. Oh and if anyone can tell me a quick solution to the warnings produced by having a vector of strings, thanks
-
#pragma warning(disable: warning number)
at the start of each file.
Well, because of the way memory allocation works in windows it might easily happen that you can write straight past the vector buffer without anyone noticing.
What you could do is forcing the vector to reallocate:
Code:
#include<iostream>
#include<string>
#include<vector>
using namespace std;
int main()
{
vector<string> strNames(3);
for( int i = 0; i < 4; i++ )
cin >> strNames[i];
// Make the vector reallocate its memory
strName.push_back("dummy1");
strName.push_back("dummy2");
cout << endl << endl;
for( i = 0; i < 3; i++ )
cout << strNames[i] << endl;
return 0;
}
This should make the fourth name disappear (but it's not guaranteed, there's a lot of uncertanity there.
You should rather go with a stack array that overflows over an integer:
Code:
int i = 13;
char str[5];
gets(str); // enter 9 characters when executing
cout << i;
Needs <iostream> and <cstdio>.
-