• +91 9723535972
  • info@interviewmaterial.com

CPlusPlus Interview Questions and Answers

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

Answer - No! It is perfectly legal, moral, and wholesome to use malloc() and delete in the same program, or to use new and free() in the same program.  But it is illegal, immoral, and despicable to call free() with a pointer allocated via new, or to call delete on a pointer allocated via malloc(). Beware! I occasionally get e-mail from people telling me that it works OK for them on machine X and compiler Y.  That does not make it right! Sometimes people say, "But I'm just working with an array of char." Nonetheless do not mix malloc() and delete on the same pointer, or new and free() on the same pointer! If you allocated via p = new char[n], you must use delete[] p; you must not use free(p).  Or if you allocated via p = malloc(n), you must use free(p); you must not use delete[] p or delete p! Mixing these up could cause a catastrophic failure at runtime if the code was ported to a new machine, a new compiler, or even a new version of the same compiler. You have been warned.

Comment(S)

Show all Coment

Leave a Comment




NCERT Solutions

 

Share your email for latest updates

Name:
Email:

Our partners