Is there any memory leak ?
const char * pname = "NAME";
char * temp = new char[strlen(Name) + 64];
sprintf(temp,"%s", pname);
delete [] temp; // is there any memory leaks because now length of temp is 4.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
No there won’t be any memory leak.
sprintfwill only use the bytes oftempthat it requires, BUT, all of the bytes initially created will remain allocated (even though some are unused).The call to
delete[] tempwill then deallocate all the bytes originally allocated.As others have pointed out though, do not free
pname. You should only calldeleteanddelete[]on pointers which were created withnewandnew[]respectively.Additional information:
When you created
temp,new[]allocated an array of contiguous bytes in memory PLUS an additional (small) space where it stores the information about the allocation (how large the allocation is, for instance). When you calleddelete[]it examined that information and found thatstrlen(Name)+64bytes were allocated, and so it knows it has to deallocate all of them. The fact that you only used a small fraction of the allocated space does not make a difference.