Lots of Memory Leaks?

Hello -

I tried to run my Bufferlist test, but I got a segmentation fault. I used valgrind and I see where the leaks are, but I don't understand what I'm doing wrong? It's saying it comes from my buffer full(), buffer enqueue, and bufferlist enqueue. I tried changing where pointers were pointing to, but it didn't really work. Any help would be appreciated.
Last edited on
A quick glance shows a problem here:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
BufferList::BufferList(int minBufCapacity){
    if (minBufCapacity < 1)
    {
        Buffer aBuffer(DEFAULT_MIN_CAPACITY);
    }
    else
    {
        Buffer aBuffer(minBufCapacity);
    }

    // THESE ARE ALL JUST LOCAL VARIABLES TO THIS FUNCTION!!!
    // YOU NEED TO REMOVE THE TYPES TO SET YOUR CLASS MEMBER VARIABLES.

    Buffer * m_cursor = nullptr;
    int m_listSize = 0;
    int m_minBufCapacity = 0;
}

You should always compile with full warnings and pay attention to those warnings.
On g++ and clang++ you need to add the flags -Wall -Wextra -Wpedantic -Wshadow
Last edited on
Another note: Your copy constructor for your Buffer appears to be incomplete.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
Buffer::Buffer(const Buffer & rhs){
    if(rhs.m_capacity > 0){
    m_capacity = rhs.m_capacity;
    }
    else {
      m_capacity = 0;
      //rhs.m_capacity = 0;
    }
    capacity();

    for(int i = 0; i < m_capacity; i++){
          m_buffer[i] = rhs.m_buffer[i];
      }
}


(1) You dereference m_buffer[i], but never initialize it.
(2) Your capacity() function is a simple getter, so your call there doesn't do anything.

As dutch mentioned, you should definitely be turning on warnings, as a lot of these issues will show up as warnings.
You dereference m_buffer[i], but never initialize it


I thought the loop itself was initializing it, since it's an array? So does that mean I have to initialize it by doing m_buffer = rhs.m_buffer ?
I also noticed a place where he's writing outside array bounds (in VLA arrays, no less!). It's in Tester::BufferEnqueueDequeue.
I thought the loop itself was initializing it, since it's an array? So does that mean I have to initialize it by doing m_buffer = rhs.m_buffer ?
Not quite. First, if you have something like:
1
2
int* ptr;
ptr[0] = 42;
this is simply bad, because ptr is not pointing to any valid memory, which is what is happening here.
Have you learned what it means for something to be a "shallow copy" vs "deep copy"?
https://www.learncpp.com/cpp-tutorial/shallow-vs-deep-copying/

m_buffer = rhs.m_buffer would be a "shallow" copy because you're just copying the pointer, but now you have two objects that are sharing one buffer of memory.

What you should be doing is something like:
m_buffer = new int[rhs.m_capacity]; to initialize your array.
Last edited on
Topic archived. No new replies allowed.