What if, memory allocated using malloc is deleted using delete rather than free

前端 未结 7 1667
渐次进展
渐次进展 2021-02-09 03:45

I came across an issue which I could not resolve.

My question is, if I used malloc to allocate memory and then memory block is delete using delete

7条回答
  •  臣服心动
    2021-02-09 03:59

    Your b variable is not a pointer, but a stack-allocated A. If you want to try this experiment, then you'd want to say

    A* b = new A;
    free(b);
    

    I'm all for experimentation, but I'm not sure what you were trying to achieve here.

    In C++, operator new doesn't just allocate memory, it runs constructors too. Similarly, delete runs destructors for you (taking polymorphic classes into account), as well as freeing the returned memory. On the other hand, malloc() and free() are just C library routines which (from a programmer's point of view) do nothing more than request a chunk of memory from the operating system, and then hand it back.

    Now, for a simple, POD class with trivial constructors and destructors, you might be able to get away with mixing up C and C++ memory allocation, because there's nothing C++-specific to be done. But even if you do, what does it prove? It's undefined behaviour, and it probably won't work on another compiler. It might not work tomorrow.

    If you use any C++ features -- inheritance, virtual functions, etc etc, it very definitely won't work, because new and delete have to do a lot more work than just allocating memory.

    So please, stick to the rules! :-)

提交回复
热议问题