我收到堆指针错误,不知道那是什么或如何解决它...帮助 [英] I am getting a heap pointer error and do not know what that is or how to fix it...help

查看:65
本文介绍了我收到堆指针错误,不知道那是什么或如何解决它...帮助的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <iostream>
#include <vector>
#include <iomanip>
#include <array>
#include <cassert>
using namespace std;

class container {
	friend ostream& operator<<(ostream& out, container &);
	// Postcondition: displays # of values stored in the container, storage capacity of the contianer, and stored values in the container 
	//                in the following format: Array size = 3, capacity = 4, contents = 11, 22, 33 (see below sample program output

public:
	container();
	// Postcondition: set dynamic storage capacity to 1 and count to -1 where (count + 1) represents the actual values stored 
	//                 in the container. Notice that data member count is used as the subscript to access elements (actual values) stored 
	//                 in the dynamic array; thus (count + 1) represents the total # of values that are currently stored in the array

	container(int n);
	// Postcondition: set dynamic storage (data array) capacity to n and count to -1

	container(container &c);
	// Programmer-supplied copy constructor is necessary to avoid memory leak and other side effect
	// Postcondition: a new container class object is created which is the same as the one passed to the function

	~container();
	// Programmer-supplied destructor is necessary to avoid memory leak
	// Postcondition: all dynamic memory locations have been returned back to the heap whenever a container object goes out of scope

	container& operator=(container &rhs);
	// Programmer-supplied overloaded assignment is necessary to avoid memory leak and other side effect
	// Postconditoin: the container object rhs is assigned to the calling object

	void insert(int value);
	// Postcondition: if the container is not full, the value passed to the function is stored in  
	//			the first available element of the dynamic array. Otherwise the function calls the private 
	//         	       "allocate" member function requesting a new set of dynamic memory with twice the previous storage capacity 
	//			the insert function then increments count by 1 and insert the value into the new and larger array.

	void remove();
	//  Precondition: the data array must not be empty; i.e., count must be greater than or equal to 0.
	// Postcondition: if the container is not empty, then remove the most recently stored value ifrom the container and 
	//			decrement count by 1; otherwise, display the message "The container is empty; no action is taken!"

	int operator[](int sub);
	//  Precondition: value passed to the function must be a positive integer including 0
	// Postcondition: the value of stored in data[sub] is returned; if sub is out of range, display a message and terminate the program .

	bool isFull();
	// Postcondition: return true if the container is full; return false otherwise 

	bool isEmpty();
	// Postcondition: return true if the container is empty; return false otherwise

	int Capacity();
	// Notice uppercase 'C' to avoid conflict with data member named "capacity"
	// Postcondition: returns the current storage capacity of the container

	int size();
	// Postcondition: returns the # of elements (# of objects) currently stored in the container

	void resize(int n);
	// Postcondition: container (i.e., the dynamic array) is resized to n; contents of existing container have been copied to the new array; 
	// 			      old array is deleted to avoid memory leak.

private:
	void allocate();
	// Postcondition: 1) the capacity of the container has been doubled, 2) existing values in the existing array have been copied to 
	//				   the new and larger dynamic array, 3) memory of the old array has been deleted (returned to "heap").

	int *data;
	int capacity;		// indicates the storage capcity of the container, i.e., the size of the dynamic array		
	int count;		// used as a subscript to index into the array; size = count + 1
};
int main()
{
	container c1;
	bool status = c1.isEmpty();
	if (status = true)
		cout << "contents of container is empty" << endl;
	else
		cout << "contianer is not empty" << endl;
	//c1.(5);
	//c1.insert(2);
	for (int i = 1; i <=9; i++)
		c1.insert(11*i);
	cout <<c1 << endl;
	/*cout << "Container c2 contains:" << endl;
	container c2(c1);
	cout<<c2<<endl;
	container c3 =c2;
	cout << "Container c3 contains:" << endl;
	cout << c3 << endl;
	c3.resize(4);
	cout << c3 << endl;
	c3.resize(7);
	cout << c3 << endl;
	cout << "Address of c1 = " << &c1 << endl;
	cout << "Address of c2 = " << &c2 << endl;
	cout << "Address of c3 = " << &c3 << endl;*/
	system("pause");
	return 0;
}
container::container()
{
	capacity = 1;
	data = new int[capacity];
	count = -1;
	assert(data !=NULL);
}
container::container(int n)
{
	count = -1;
	capacity = n;
	data = new int[capacity];
	assert(data !=NULL);
}
container::container(container &c)
{
	capacity = c.capacity;
	count=c.count;
	data = new int[capacity];
	assert(data !=NULL);
	for (int i = 0; i < capacity; i++)
		data[i] = c.data[i];
}
container::~container()
{
	delete[]data;
}
container& container:: operator=(container &rhs)

{
	if (this != &rhs)
	{
		delete data;
		data = rhs.data;
		rhs.data = nullptr;
	}
	return (*this);

}

void container::insert(int x)
{
	//cout << count;
	if (isFull())
		++count;
	(*this).allocate();
	(*this).data[count] = x;
}

bool container::isFull()
{
	bool status;

	if (count == capacity - 1)
		status = true;
	else
		status = false;
	return status;
}
void container::allocate()
{
	int *temp;
	temp = new int[2 * capacity];
	for (int i = 0; i < count; i++)
		temp[i] = data[i];
	capacity = 2 * capacity;
	for (int i =0; i<count; i++)
	data = temp;
	delete[]data;
}
int container::operator[] (int sub)
{
	int num;
	if (sub<0)
	{

		cout << "sub is out of range";
		exit(1);
	}
	num = data[sub];
	return num;
}
bool container::isEmpty()
{
	if (count == -1)
		return true;
	else
		return false;
}
ostream& operator<<(ostream& out, container & obj)
{

	out << "The 'container' contains the following " << obj.count + 1 << " value(s):\n";
	if (obj.count == -1)
		out << "*** data array is empty!" << endl;
	else
	{
		for (int i = 0; i <= obj.count; i++)
			out << obj.data[i] << '\t';
		out << endl;
	}
	return out;
}
int container::Capacity()
{
	return capacity;
}
void container::resize(int n)
{
	int *temp;
	temp = new int[n];
	assert(temp != NULL);
	if (count + 1 < n)
		for (int i = 0; i <= count; i++)
			temp[i] = data[i];
	else
	{
		for (int i = 0; i < n; i++)
			temp[i] = data[i];
		count = n - 1;
	}
	capacity = n;
	delete[] data;
	data = temp;

}





我的尝试:



i am jsut试图让它运行



What I have tried:

i am jsut trying to make it run

推荐答案

有多个错误。如果已经为您的代码添加了一些注释。请注意,我可能也错过了一些错误。





访问位于其上的对象元素时会引发堆错误堆(使用 new 或其中一个C分配函数,如 malloc )超出范围。对于数组,当使用超出数组大小的索引(索引> =大小或负数)时会发生这种情况。当内存指针无效时( NULL ,未定义或随机值,或者同时删除了内存)也会发生这种情况。

[/编辑]



There are multiple errors. If have added some comments to your code. Note that I may have also missed some errors.


A heap error is thrown when accessing elements of objects located on the heap (allocated using new or one of the C allocation functions like malloc) out of bounds. With arrays this happens when using an index that is beyond the array size (index >= size or negative). It happens also when the memory pointer is invalid (NULL, an undefined or random value, or the memory has been deleted meanwhile).
[/EDIT]

container& container:: operator=(container &rhs)
{
    if (this != &rhs)
    {
        delete data;
        data = rhs.data;
        rhs.data = nullptr;
        // What happens when rhs.capacity or rhs.count are not identical 
        //  to this->capacity and this->count ?
        // Especially when the rhs values are smaller and 
        //  acessing an element beyond the data size later?
        // What happens when accessing elements of rhs afterwards?
        // Tip: The count and capacity members of rhs still indicate that there are data
    }
    return (*this);
}




void container::allocate()
{
    int *temp;
    temp = new int[2 * capacity];
    for (int i = 0; i < count; i++)
        temp[i] = data[i];
    capacity = 2 * capacity;
    // ??? 
    // Not an error but useless
    // I have indented the follwing line to show what happens
    for (int i =0; i<count; i++)
        data = temp;
    // You are deleting the newly created storage here!
    // This must be moved up before the
    //  data = temp 
    // statement to delete the old array.
    delete[]data;
}




int container::operator[] (int sub)
{
    int num;
    if (sub<0)
    {
        cout << "sub is out of range";
        // Why do you use exit here?
        // Throwing an exception would be the common C++ method
        exit(1);
    }
    // What happens when sub is greater than count?
    num = data[sub];
    return num;
}







解决方案:

你有三个成员变量,表明你的容器的状态:

数据容量,和 count

执行操作时,如果受操作影响,必须确保所有操作都更新。

[/ EDIT ]




Solution:
You have three member variables that indicate the state of your container:
data, capacity, and count
When performing operations you must ensure that all are updated if affected by the operation.
[/EDIT]


尝试告诉我们错误发生的位置。



你应该学会尽快使用调试器。而不是猜测你的代码在做什么,现在是时候看到你的代码执行并确保它完成你期望的。



调试器允许你跟踪执行逐行检查变量,你会看到它有一个停止做你期望的点。

调试器 - 维基百科,免费的百科全书 [ ^ ]

掌握Visual Studio 2010中的调试 - A初学者指南 [ ^ ]



调试器在这里向您展示您的代码正在做什么,您的任务是与它应该做什么进行比较。 />
当代码不做ex的时候你已经接近了一个错误。
Try to tell us where the error occurs.

You should learn to use the debugger as soon as possible. Rather than guessing what your code is doing, It is time to see your code executing and ensuring that it does what you expect.

The debugger allow you to follow the execution line by line, inspect variables and you will see that there is a point where it stop doing what you expect.
Debugger - Wikipedia, the free encyclopedia[^]
Mastering Debugging in Visual Studio 2010 - A Beginner's Guide[^]

The debugger is here to show you what your code is doing and your task is to compare with what it should do.
When the code don't do what is expected, you are close to a bug.


这篇关于我收到堆指针错误,不知道那是什么或如何解决它...帮助的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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