Corrupted stack error

Hey guys i have to write 50000 words randomly in a text file... so I wrote this code :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <cstdlib>
#include <fstream>
using namespace std;
int main()
{
	ofstream myfile ("dictionary.txt");
	for (int i=0; i<50000; i++)
	{
		int max=rand()%4+2;
		char word[5];
		for (int j=0; j<max; j++)
		{
			int word1=rand()%26+97;
			word[j]=char(word1);
		}
		word[max]='\0';
		myfile<<word<<endl;
	}
	myfile.close();
}

And when I run it a run time error appears : Run-Time Check Failure #2 - Stack around the variable 'string' was corrupted ... I dunno what's the problem .
You are overrunning word (defined on line 11) at line 17 because max can reach a value of 5.
I wrote it because I wanted to write the words only in the text file ... without the line 17 the words will be like : abcdIIIII and qdndwIIIIII ... I don't want the extra characters any other way to do that ?
You could make word an array of size 6.
Last edited on
Yes, if you do your math properly.

Ask yourself what does rand()%4 + 2 return?
What's the smallest number and what's the largest number?
How does this compare with Line 11?
Is Line 17 ok given the entire range of max?

Hint: Remember, char word[5] means you can only go from 0 to 4, including the null terminating character.
Last edited on
Topic archived. No new replies allowed.