I ve the following memory allocation done
int *a;
a=malloc(5*sizeof(int));
Is there a way to just free say the 5th location of this set?
ie can I do free(a+4)??
Currently this gives a segmentation fault error.
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, you cannot do
free(a+4)etc.Why? Because the C standard forbids it.
You must pass the exact pointer returned by
malloc()tofree()without any pointer arithmetic.http://www.kernel.org/doc/man-pages/online/pages/man3/free.3.html
Why the standard forbids it? It is because some implementations of
malloc()stores header information at the locationa-4(or wherever) andfree()internally reads it by pointer arithmetic. If it’s given a shifted pointer likea+4, it will miss the header info and get screwed.Cf.
Incidentally some libc implementations provide non-standard functions which return the size of the allocated memory chunk:
If you’re curious how they’re implemented and look into their source code, you often find that they read the header info at
a-4etc:OK, back to the original question.
If you want to shorten (or lengthen) the memory chunk you allocated with
malloc(), you can userealloc()as @Gustav said. But if you want to remove a few bytes from the middle of your memory chunk, you need manual re-allocation and copying. Actuallyrealloc()might internally do a similar work, so be careful with the returned pointer which may be different from the original one.