Segmentation Fault in Stack

Hi,

For some reason I can't seem to understand why the while loop at line 45 is causing an out of bounds error?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#include<iostream>
#include<cstring>
#include<stack>

using namespace std;

void GetData(char key1[5], char key2[5], char phrase[100])
{
 cout << "Please enter the first four-character key: ";
 
 cin.getline(key1, 5);

 cout << "\nPlease enter the second four-character key: ";
 
 cin.getline(key2, 5);

 cout << "\nPlease enter the phrase you would like to encrypt: ";
 
 cin.getline(phrase, 100);

 return;
}

int main()
{
 char key1[5],
      key2[5],
      phraseIn[100];

 stack<char> myStack;

 GetData(key1, key2, phraseIn);

 cout << "\n" << key1 << "\t" << key2 << "\t" << phraseIn << endl;

 cout << "\nThe encrypted message is: ";

 for(int i = 0; i < strlen(phraseIn); i++)
  {
   myStack.push(phraseIn[i]);
   
   if((myStack.top() == key1[0]) || (myStack.top() == key1[1]) || 
      (myStack.top() == key1[2]) || (myStack.top() == key1[3]))
    {
     while((myStack.top() != key2[0]) && (myStack.top() != key2[1]) && 
           (myStack.top() != key2[2]) && (myStack.top() != key2[3]) && (!myStack.empty()))
	{
	 cout << myStack.top();
	 myStack.pop();
	}

    } 
  }

 while(!myStack.empty())
  {
   cout << myStack.top();
   myStack.pop();
  }

 return 0;
}



Please enter the first four-character key: GOOD

Please enter the second four-character key: LUCK

Please enter the phrase you would like to encrypt: SOUNDS SIMPLE TO ME

Segmentation fault


Thanks in advance for any input.
closed account (DSLq5Di1)
1
2
     while((myStack.top() != key2[0]) && (myStack.top() != key2[1]) && 
           (myStack.top() != key2[2]) && (myStack.top() != key2[3]) && (!myStack.empty()))

You should test if the stack is empty before trying to access the next element.
Thanks for some input I really appreciate it.

I tried that before and again just now however it still produces the same error.
closed account (DSLq5Di1)
Mmm, I just copy'pasted it into ideone (http://ideone.com/s9dtV) with that modification and it seems to be working.. is there anything I'm missing?
I just took at look at yours we had the exact same thing except I had an extra pair of parenthesis. I am assuming it was causing some sort of short-circuiting.

It is working now though. Thanks for all of your help.
Topic archived. No new replies allowed.