c++ - Releasing memory space allocated by new using free() -
as understand, delete[] used release memory space allocated new. free() can used release memory space. type of problems have face when releasing memory using free() in place of delete[]?
"
free()can used release memory space."
no, free() cannot used release memory allocated new() or new[].
"so type of problems have face when releasing memory using
free()in place ofdelete[]?"
using free() instead of delete[] memory allocated new[] undefined behavior (besides destructor functions of complex objects won't called), , such may end runtime exception.
from posix compliant reference (emphasis mine):
the
free()function shall cause space pointed ptr deallocated; is, made available further allocation. if ptr null pointer, no action shall occur. otherwise, if argument not match pointer earlier returnedcalloc(),malloc(),posix_memalign(),realloc(), orstrdup()function, or if space has been deallocated call free() orrealloc(), the behavior undefined.any use of pointer refers freed space results in undefined behavior.
well, implementations of new[] or new() might rely on malloc() function family, others may not. can't tell allocated memory pointer can safely used free (even if don't care destructor function call issue).
conclusion:
usage of delete[] defined operate on memory allocated using new[], delete corresponds results of new.
as usage of free() defined in conjunction memory allocated using malloc() function family.
as far concerning c tag applied (original) question, since c doesn't support delete or new asking c language pretty useless.
Comments
Post a Comment