can i free pointers allocated along with new


Can I free() pointers allocated  along with new? Can I delete pointers allocated along with malloc()?

A: No.

It is completely legal, moral, and wholesome to employ malloc() and delete in the same program, or to employ new and free() in the same program. However it is illegal, immoral, & despicable to call free() along with a pointer allocated though new, or to call delete on a pointer allocated through malloc().

Occasionally people tell that it works OK for them on machine X and compiler Y. Just because they don't notice bad symptoms in simple test case doesn't mean this won't crash in the field. Even if they know this won't crash on their specific compiler doesn't mean this will work carefully on another compiler, platform, or even another version of the simialr compiler.

Occasionally people say, "But I'm just working with an array of char." Though do not mix malloc() and delete on the similar pointer, or new & free() on the similar pointer! If you allocated through p = new char[n], you have to use delete[] p; you do not have to use free(p). Or if you allocated via p = malloc(n), you have to use free(p); you should not employ delete[] p or delete p! Mixing these up could cause a catastrophic failure at runtime if code was ported to a new compiler, a new machine or even a new version of the similar compiler

 

Request for Solution File

Ask an Expert for Answer!!
C/C++ Programming: can i free pointers allocated along with new
Reference No:- TGS0217518

Expected delivery within 24 Hours