[英]c++ code works properly but the process ends with termination instead return 0
i wrote a simple c++ code in codeblocks and i implemented stack and graph classes for that with dynamic memory allocation.我在代码块中编写了一个简单的 C++ 代码,并通过动态内存分配实现了堆栈和图形类。 my code works properly and gives correct output but at the end it shows ***.exe has stopped working error and shows "Process terminated with status -1073741819" in build log.
我的代码工作正常并提供正确的输出,但最后它显示 ***.exe 已停止工作错误并在构建日志中显示“进程终止状态为 -1073741819”。 i tried GNU gdb 6.8 debugger and it couldn't find any errors.
我尝试了 GNU gdb 6.8 调试器,但找不到任何错误。
this problem was made after imlementing stack class, so this is my code if it can helps solving problem:这个问题是在实现堆栈类之后产生的,所以这是我的代码,如果它可以帮助解决问题:
class stack
{
vertex* d;
int end;
public:
stack()
{
end=0;
d=NULL;
}
void create(int n)
{
d=new vertex[n];
}
vertex top()
{
return d[end];
}
void push(vertex y)
{
end++;
d[end]=y;
}
vertex pop()
{
end--;
return d[end+1];
}
~stack()
{
if (d!=NULL)
delete d;
}
};
edit: main asked:编辑:主要问:
int main()
{
G graf;
graf.get();
stack tree;
tree.create(graf.q()-1);
int q=0;
int i=0;
int u=0;
while (u<graf.q()-1)
{
tree.push(graf.u[i]);
if (graf.u[i].r[0]->flag > 0 && graf.u[i].r[1]->flag > 0 && u>=q)
tree.pop();
else
{
u++;
if (graf.u[i].r[0]->flag==0)
q++;
if (graf.u[i].r[1]->flag==0)
q++;
graf.u[i].r[0]->flag++;
graf.u[i].r[1]->flag++;
cout << tree.top().r[0]->name << " - " << tree.top().r[1]->name << '\n';
}
i++;
}
return 0;
}
Your code is wrong:你的代码是错误的:
void push(vertex y)
{
end++;
d[end]=y;
}
Should be:应该:
void push(vertex y)
{
d[end]=y;
end++;
}
Else, first pushed item goes to position 1
instead of position 0
.否则,第一个推送的项目会转到位置
1
而不是位置0
。
Moreover, stack::top()
returns next item, not last pushed:此外,
stack::top()
返回下一项,而不是最后推送:
vertex top()
{
return d[end];
}
should be:应该:
vertex top()
{
return d[end-1];
}
I'm pretty sure you seg fault is due to unallocated memory being accessed, add assertions to have the program notify you when something gets wrong, like that:我很确定你的段错误是由于未分配的内存被访问,添加断言让程序在出现问题时通知你,就像这样:
class stack
{
vertex* d;
int cur;
int capacity;
public:
stack()
{
cur=0;
capacity=0;
d=NULL;
}
void create(int n)
{
assert( d == NULL );
capacity = n;
d=new vertex[n];
}
vertex top()
{
assert( cur != 0 );
return d[cur-1];
}
void push(vertex y)
{
cur++;
assert( cur < capacity );
d[cur]=y;
}
vertex pop()
{
assert( cur > 0 );
cur--;
return d[cur+1];
}
~stack()
{
if ( d != NULL )
delete [] d;
}
};
Then, run again, you'll see where you get an assertion.然后,再次运行,您将看到在何处获得断言。
Finally, check vertex
copy constructor works fine, because pushing/poping does a lot of vertex
copy, if there's something wrong here, it could cause seg fault.最后,检查
vertex
复制构造函数是否工作正常,因为push/poping做了很多vertex
复制,如果这里有问题,可能会导致seg fault。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.