Memory fault for circular buffer

Hey guys I keep encountering a memory fault trying to call a class member function. Does anyone know why? Am I accessing something I shouldn't be? Thanks.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
//.cpp (implementation file) 
void Deque::checkCapacity() {
     if (size == capacity) {
        EType *temp = new EType[2*capacity];
        for (int i = 0; i < capacity; i++)
            temp[i] = arr[i];
        delete [] arr;
        arr = temp;
        capacity = 2*capacity;
     }
}

void Deque::insert_front(const EType &data) {
         checkCapacity();
         front--;
         if (front < 0) front = capacity-1;
         arr[front] = data;
         size++;
}

//demo.cpp
for (int i = 0; i < 30; i++) {
        if(i % 2 == 0) {
                deque1.insert_front(i); //causes memory fault
        } else {
                deque1.insert_front(i); //as well
        }
}
EDIT: never mind.

Need to see more of your code to know what's going on. Specifically, what are the values of size, capacity, and front for deque1 when entering the loop. Also your class definition (just the header file will do).

Not related to your current problem, but consider the case of calling insert_front when

front == 0
size == capacity
capacity >= 2


From arr[size - 1] to arr[front - 1] will be garbage values. Not sure if that's what you want.
Last edited on
Thanks for the reply here it is.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
//.h
typedef int EType;
 
class Deque {
          friend std::ostream &operator <<(std::ostream &os, const Deque &deque);
 public:
          Deque();
          void set();
          void checkCapacity();
          void insert_front(const EType &data);
          //... (other functions) 
 private:
          int size, capacity;
          int front, rear;
          EType *arr;
          static const int INITIAL_CAPACITY = 10;
 };

//.cpp - as stated above 
void Deque::set() {
        size = 0;
        capacity = INITIAL_CAPACITY;
        front = 1;
        rear = front-1;
}

//demo.cpp - as stated above  


I forgot to mention I added a set function for the values. But with or without that function I was encountering the memory fault.
Last edited on
Looking at your code, the problem with garbage values wouldn't happen. Bad guess on my part.

1
2
3
4
5
6
void Deque::set() {
        size = 0;
        capacity = INITIAL_CAPACITY;
        front = 1;
        rear = front-1;
}

You didn't allocate memory for your array here. Did you do it in the constructor?
Last edited on
Sorry for late reply but you were correct I hadn't allocated the memory for it. Thanks. :)
Topic archived. No new replies allowed.