I wrote my implementation of Vector class but when my program is running, I'm getting CrtlsValidHeapPointer(block) error only when reallock function is called. Below is my code.
#include "IntVector.h"
#include <stdlib.h>
#include <iostream>
using namespace std;
IntVector::IntVector() {
this->size = 0;
this->arr = (int*)malloc(sizeof(int));
this->arr[0] = 1;
}
int IntVector::getsize() {
return this->size;
}
int IntVector::get(int index)
{
if (index >= size) {
exit(0);
}
return this->arr[index];
}
void IntVector::add(int n) {
this->size++;
int* p = (int*)realloc(this->arr, this->size * sizeof(int));
this->arr = p;
this->arr[size - 1] = n;
}
void IntVector::remove(int index) {
if (index < this->size && size > 0) {
this->size--;
int* newarr = (int*)malloc((this->size) * sizeof(int));
int j = 0;
for (int i = 0; i < size + 1; i++) {
if (i == index) continue;
newarr[j] = this->arr[i];
j++;
}
free(this->arr);
this->arr = newarr;
}
}
int IntVector::getindex(int item)
{
for (int i = 0; i < this->size; i++) {
if (this->arr[i] == item) {
return i;
}
}
return -1;
}
I analyzed rest of my code and I think that problem lies in this class. Values in my program are correct until error is thrown.