Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Cannot delete array without read access violation

I recently wanted to make a quick emulator in C++ without using the C++ (C is allowed) standard library features. Thus, I used raw pointer arrays to store the memory of my emulator. However, I encountered a read access violation while moving my memory class to another memory class. All suggestions are welcome.

Memory class:

#ifndef MEM_HPP
#define MEM_HPP

#include <cstdint>
#include <cstddef>

namespace handle {
    using num = std::uint8_t;
    using size = std::size_t;
    struct memory {
        enum { EIGHT_BIT_MAX_MEM = 256, SIXTEEN_BIT_MAX_MEM = 65536 };
        constexpr explicit memory(size max_mem) : mem_size(max_mem) {
            mem = new num[max_mem];
        }
        constexpr memory(memory&& other) noexcept {
            delete[] mem;
            mem = other.mem;
            mem_size = other.mem_size;
            other.mem = nullptr;
            other.mem_size = 0;
        }
        constexpr memory(const memory& other) = delete;
        constexpr ~memory() {
            delete[] mem;
        }
        constexpr memory& operator=(memory&& other) noexcept {
            delete[] mem;
            mem = other.mem;
            mem_size = other.mem_size;
            other.mem = nullptr;
            other.mem_size = 0;
            return *this;
        }
        constexpr num& operator[](num loc) {
            return mem[loc];
        }
        constexpr size get_mem_size() const noexcept {
            return mem_size;
        }
        num *mem;
        size mem_size;
    };
}

#endif /* MEM_HPP */

main.cpp:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#include <type_traits>
#include "mem.hpp"

int main() {
    using namespace handle;
    memory m{ memory::EIGHT_BIT_MAX_MEM };
    memory other{ std::move(m) };
}

EDIT:
Even when I remove the constructor that initializes memory to null pointer, I still get the read access violation.

>Solution :

delete[] mem; is an attempt to delete a not yet allocated memory in the move-constructor. Remove that line.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading