|
-
Feb 7th, 2003, 06:01 PM
#1
Thread Starter
Fanatic Member
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
The human brain cannot hold all of the knowledge that exists in this world, but it can hold pointers to that knowledge.
-
Feb 8th, 2003, 07:06 PM
#2
#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>.
All the buzzt
 CornedBee
"Writing specifications is like writing a novel. Writing code is like writing poetry."
- Anonymous, published by Raymond Chen
Don't PM me with your problems, I scan most of the forums daily. If you do PM me, I will not answer your question.
-
Feb 8th, 2003, 07:24 PM
#3
Thread Starter
Fanatic Member
The human brain cannot hold all of the knowledge that exists in this world, but it can hold pointers to that knowledge.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|