K
K
Kirill Zhilyaev2018-05-17 20:07:15
C++ / C#
Kirill Zhilyaev, 2018-05-17 20:07:15

Why does a segmentation fault occur?

There is a code

void *operator new( size_t stAllocateBlock ) throw (std::bad_alloc)
{
        void *point = malloc( stAllocateBlock );

        if( point != NULL  )
                BLOCKS[point] = stAllocateBlock;

        return point;
}

But for some reason, when perovm new - crash

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman, 2018-05-18
@kirill_782

for map to which you address the same operator new is called.
it turns out you are accessing the BLOCKS object before it is created.

spoiler
#include <cstdio>
#include <cstdlib>
#include <map>
std::map<void*, size_t> BLOCKS;

void* operator new(std::size_t sz) {
    std::printf("global op new called, size = %zu\n",sz);
    void* p = std::malloc(sz);
    //if(p) BLOCKS[p] = sz;
    return p;
}
void operator delete(void* ptr) noexcept
{
    std::puts("global op delete called");
    std::free(ptr);
}
int main() {
     int* p1 = new int;
     delete p1;
}

global op new called, size = 48
global op new called, size = 4
global op delete called
global op delete called

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question