Unable to access object function after direct call to `operator new`

I am working on a project that needs to implement new operatorboth delete operator, and manage its memory with its own MemoryManager - which has lists of available memory.

To highlight my lists and nodes (which should not be managed), I must explicitly call operator newafter the call malloc.
When I try to call the - function setNext(), it throws an exception: Exception: EXC_BAD_ACCESS (code = 1, address = 0x0)

Creating a HashTable from LinkedLists:

MyHashTable::MyHashTable(size_t memorySize, void* startingPtr)
        :size(getLowerLog(memorySize) + 1), lists((LinkedList**)malloc(sizeof(LinkedList*) * size)), startingPtr(startingPtr) {
    for (size_t i = 0; i < size; i++) {
        auto memSize = (size_t) pow(2, i);
        void * l = malloc(sizeof(LinkedList));
        lists[i] = new (l) LinkedList(memSize);
        // Placement new
    }
    dividingMemory(memorySize, startingPtr);
}

The function dividingMemorydoes:

void MyHashTable::dividingMemory(size_t memorySize, void* startingPtr) {
    while (memorySize > 0) {
        size_t memPow = getLowerLog(memorySize);
        auto max = (size_t) pow(2, memPow);
        lists[max]->add(ptr);              // here is the call to LinkedList::add()
        startingPtr = ((char*) startingPtr) + max;
        memorySize -= max;
    }
}

LinkedList :: add ():

void LinkedList::add(void * ptr) {
    void* p = malloc(sizeof(Node));
    Node * newNode = new (p) Node(ptr);
    // Placement new
    newNode->setNext(head);
    std::cout << "haha" << std::endl;
    head = newNode;
    size++;
}

Whole class Node: Node.h:

#ifndef EX3_NODE_H
#define EX3_NODE_H
#include <iostream>
#include <string>
class Node {
private:
    void* ptr;
    Node* next;
public:
    explicit Node(void*);
    inline Node* getNext() const {
        return next;
    }
    inline void setNext(Node* next) {
        this->next = next;
    }
    ~Node() = default;
};
#endif //EX3_NODE_H

Node.cpp

Node::Node(void * ptr):ptr(ptr) { }

I tried calling another function (toString) and it was disabled.

What am I doing wrong?

@Ben Voigt, .

+4
2

, undefined.

auto max = (size_t) pow(2, memPow);
lists[max]->add(ptr);

:

auto max = (size_t) pow(2, memPow);
lists[(log(max) / log(2)]->add(ptr);
0

new, . - raw-storage, . .

malloc :

void* rawBlock = malloc(sizeof(Node));
Node* newNode = new (rawBlock) Node(ptr);

// later
newNode->~Node();
free(rawBlock);
+3

Source: https://habr.com/ru/post/1692112/


All Articles