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

前端 未结 7 1709
渐次进展
渐次进展 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 04:05

    You didn't create b using new so you are not testing the intended hypothesis. (Also, the name of b is not a pointer.)

    Anyway, malloc/new and delete/free work interchangeably only as long as their implementations are interchangeable. In simple cases and on simpler platforms this is more likely, but it's a risky bet in the long term or as a habit.

    For example, the array form of new, when applied to a class with a nontrivial destructor, requires the implementation (compiler, runtime, etc.) to remember the size of the array so that delete may call the destructor for each array object. There is almost nowhere to put such information but in the dynamically allocated block itself, preceding the memory location referred to by the pointer returned by new. Passing this pointer to free would then require the memory allocator to determine the actual start of the allocation block, which it may or may not be able to do.

    More generally, new and malloc may refer to completely different memory allocators. The compiler, runtime library, and OS work together to provide memory to your program. The details can change as a result of switching or upgrading any of these components.

提交回复
热议问题