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

前端 未结 7 1668
渐次进展
渐次进展 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:58

    The free function expects a pointer to memory allocated by malloc. The compiler is simply telling you that did not pass it a pointer, a fact that it can readily prove. I guess you meant to create an object with new and then call free on the address of that object. But you did not call new.

    When you correct this you may well find the free succeeds but you should not read anything significant into any such success. You know the rules, they are clearly stated in your documentation. It is incorrect to do what you are attempting. The behaviour is undefined. There's little to be gained from an experiment like this. You won't learn anything about why the C memory management functions cannot be paired with C++ memory management functions.

    The problem with your experiment is that is has no power. You can just show the outcome for one specific scenario. But these functions are designed to work across the board. How are you going to test every single possible scenario?

    Never program using trial and error. You must always understand the rules and priciples behind what you do.

提交回复
热议问题