0

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.

1
  • 7
    You are calling delete[] mem; in your move constructor when the value of mem has not been set yet. The line doesn't belong there at all. I am voting to close as typo. Commented Jan 29, 2022 at 21:29

1 Answer 1

5

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.