moonasteroid
moonasteroid

Reputation: 65

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:

#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.

Upvotes: 0

Views: 106

Answers (1)

3CxEZiVlQ
3CxEZiVlQ

Reputation: 38834

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

Upvotes: 5

Related Questions