当我调试时,程序在subset()
的第3行崩溃。
运行程序和调试有两张图片......
#include <iostream>
#include <cmath>
#include <cstdio>
#include <stack>
using namespace std;
int c[6];
char s[101];
int end, yes;
stack<char> sstk;
stack<int> nstk;
int toInt(char ch)
{
int temp;
switch(ch)
{
case 'p': temp = c[0];
break;
case 'q': temp = c[1];
break;
case 'r': temp = c[2];
break;
case 's': temp = c[3];
break;
case 't': temp = c[4];
break;
default:
cout<<"Char incorrect :"<<endl;
}
return temp;
}
int oper(int x, int y, char ch)
{
switch(ch)
{
case 'K':
if(1 == x && 1 == y)
return 1;
else
return 0;
case 'A':
if(0 == x && 0 == y)
return 0;
else
return 1;
case 'C':
if(1 == x && 0 == y)
return 0;
else
return 1;
case 'E':
if(x == y)
return 1;
else
return 0;
default:
cout<<"Operation error"<<endl;
return -1;
}
}
bool isOper(char ch)
{
switch(ch)
{
case 'K': case 'A': case 'N': case 'C': case 'E':
return true;
default:
return false;
}
}
int isTau()
{
char a, b, p, t;
int f; //f==1 means the char was asigned
p = s[0]; cout<<"A time p="<<p<<endl;
if(p == 0)
return -1;
if(!isOper(p) )
return 0;
int i = 1;
while((t=s[i++]) != '!')
{ cout<<t<<endl;
if(isOper(t) ) //If the t char is operator, push previous opertator
{
if(1 == f) //and push the a operand if there is one
nstk.push(a);
sstk.push(p);
p = t; //replace the p with t
f = 0;
continue;
}
int num = toInt(t); //If t is not operatand, trans it to int
if(p == 'N') //To operate either there is an N or f==1(a, b, p)
{
b = (num == 1 ? 0 : 1);
}
if(1 == f)
{
b = oper(a, num, p);
}
else
{
a = num;
f = 1;
continue;
}
while(!sstk.empty() )
{
p = sstk.top();
if('N' == p)
{
b = (b == 1 ? 0 : 1);
sstk.pop();
continue;
}
a = nstk.top();
b = oper(a, b, p);
nstk.pop();
sstk.pop();
}
a = b;
f = 0;
}
if(1 == a)
return 1;
else
return 0;
}
void subset(int n,int *A, int cur)
{
for(int i=0; i<cur; i++)
{ cout<<A[i]<<" ";
c[A[i]] = 1;
} cout<<endl;
if(cur != 0)
{
int t = isTau(); //cout<<"Is Tas: "<<t<<endl;
if(t == -1)
{
end = 1;
return;
}
if(t == 0)
yes = 0;
}
int s = cur ? A[cur-1]+1 : 0;
for(int i=s; i<n; i++)
{
A[cur] = i;
subset(n, A, cur+1);
if(end == 1)
return;
}
}
int main()
{
freopen("input.txt","r",stdin);
do
{ cout<<"Loop : "<<endl;
int i;
char t;
for(i=0; (t=getchar() ) != '\n'; i++)
{
s[i] = t;
}
s[i] = '!';
int *a;
subset(5,a,0); cout<<"what?";
if(yes == 1)
cout<<"tautology"<<endl;
else
cout<<"not"<<endl;
}while(end == 0);
return 0;
}
答案 0 :(得分:0)
int *a;
subset(5,a,0); cout<<"what?";
此处a
被定义为指向整数的指针,但从未初始化。然后传递给subset
,试图取消引用它......
cout<<A[i]<<" ";
...导致UB(未定义的行为)。从那里发生的一切,包括崩溃,都是UB的可能结果。
您可以在使用之前将a
指向已分配的缓冲区:
int *a = new int[5]; // uninitialized, use instead 'new int[5]();' to initialize to all-0
subset(5,a,0); cout<<"what?";
// ...
// remember to 'delete [] a;' when no longer used
或者您可以将a
更改为本地数组:
int a[5]; // uninitialized, use instead 'int a[5] = { 0 };` to initialize to all-0
subset(5,a,0); cout<<"what?";