堆的破坏 [英] curruption of the heap

查看:81
本文介绍了堆的破坏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include "StdAfx.h"
#include<iostream>
using namespace std;

class stream
{
	char *name_of_stream;
	int year_of_starting;
	public:
	void set_stream(char *n,int y)
	{
		name_of_stream=n;
		year_of_starting=y;     //error comes at this point
		
	}
	void get_stream()
	{
		cout<<name_of_stream;
		cout<<year_of_starting;
		
	} 
};
class students:public stream
{
	char *stud_name;
	int stud_rollno;
	public:
	void set_data(char *n,int r)
	{
		stud_name=n;
		stud_rollno=r;
	}
	void get_data()
	{
		cout<<stud_name;
		cout<<endl<<stud_rollno;
	}			
};
int main()
{
	students *s;
	int num=0;
	s=new students[num];
	char c;
	char stream[10],name[50];
	int year;
	double rollno;
	do
	{
		cout<<"enter the stream";
		cin>>stream;
		cout<<"enter the year of joining the college"<<endl;
		cin>>year;
		cout<<"enter your name";
		cin>>name;
		cout<<"enter your rollno";
		cin>>rollno;
		(s+num)->set_data(name,rollno);
		(s+num)->set_stream(stream,year);
		num++;
		cout<<"do you want to continue  (y/n)";
		cin>>c;
	}while(c!='n');
	cout<<num;
	for(int i=0;i<num;i++)
	{
		(s+i)->get_data();
		(s+i)->get_stream();
	}
	delete s;
	return 0;
}



在main()中执行do-while循环后程序无法运行



错误是: -

Windows在projectname.exe中触发了一个断点。



这可能是由于腐败造成的堆的,表示projectname.exe或它已加载的任何DLL中的错误。



这也可能是由于用户在database_of_student时按F12。 exe有焦点。



输出窗口可能包含更多诊断信息。







请帮帮我

thnx提前


the program doesn't run after executing the do-while loop in main()

error is:-
Windows has triggered a breakpoint in "projectname.exe".

This may be due to a corruption of the heap, which indicates a bug in projectname.exe or any of the DLLs it has loaded.

This may also be due to the user pressing F12 while database_of_student.exe has focus.

The output window may have more diagnostic information.



please help me
thnx in advance

推荐答案

部分问题在于:< br $> b $ b

Part of your problem is here:

    int num=0;
s=new students[num];





您正在创建一个零元素长的新学生阵列。因此,每次推进指针都会破坏内存。您需要分配尽可能多的元素,或者如果想要动态分配,请使用某种链接列表或向量。



此外,您还要添加num使用num ++,它只会使指针sizeof(int)前进,这将覆盖student数组中的数据。你需要通过sizeof(学生)推进指针,而不仅仅是num ++。你试图使用num作为迭代器和计数器,这是行不通的。你需要将两者分开,有一个计数和一个指向当前元素的指针。



you are creating a new array of students that's zero elements long. So every time you advance the pointer you are corrupting memory. You need to allocate as many elements as you are going to use, or use some sort of linked list or vector if you want dynamic allocation.

Also you are adding to num by using num++, which only advances the pointer sizeof(int), which is going to overwrite data in your students array. You need to advance the pointer by sizeof(students), not just num++. You are trying to use num as both an iterator and a counter, which isn't going to work. You need to separate the two, have a count, and a pointer to your current element.


这篇关于堆的破坏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆