问题遇到的现象和发生背景
我想要自己实现一个vector头文件。代码如下:
#ifndef _MY_VECTOR_H
#define _MY_VECTOR_H
template<class T>
class my_vector
{
public:
my_vector(int size)
{
this->data = (T*)malloc(sizeof(T) * size);
this->_size = size;
for (int i = 0; i < size; i++)
{
*(data + i) = NULL;
}
}
my_vector()
{
this->data = (T*)malloc(sizeof(T) * 10);
this->_size = 10;
}
~my_vector()
{
free(this->data);
}
void push_back(T data)
{
for (int i = 0; i < this->_size; i++)
{
if (!(*(this->data + i)))
{
(*(this->data + i)) = data;
return;
}
}
re_malloc(this->_size+5);
push_back(data);
}
T* get_values()
{
return this->data;
}
private:
int _size;
T* data;
void re_malloc(int size)
{
int old_size = this->_size;
T* old_point = this->data;
this->data = (T*)malloc(sizeof(T) * size);
this->_size = size;
// 给新空间标NULL
for (int i = this->_size; i < this->_size; i++)
{
*(this->data + i) = NULL;
}
//复制
for (int i = 0; i < old_size; i++)
{
*(this->data + i) = *(old_point + i);
}
free(old_point);
}
};
#endif
主程序:
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include "my_vector.h"
using namespace std;
int main()
{
my_vector<int> vector(2);
vector.push_back(12321);
vector.push_back(1232124324);
vector.push_back(12341321);
int* data = vector.get_values();
cout << *data << endl;
cout << *(data + 2) << endl;
}
运行结果及报错内容
报错stack overflow。
位置在re_malloc()函数中。
我想要达到的结果
正常跑而且内存安全,求解!
希望大家指点我哪里错了!