i just experiment the things on the c language
could you answer my question regarding the program i’ve written
void main()
{
char *p,; // created a pointer pointing to string
p = (char *) malloc(50); // dynamically create 50 bytes.
strcpy(p, "this code is written about the dynamic allocation");
p += 20;
free(p);
}
Now could anyone tell me what is the effect of free(p) statement will the last 30 bytes will be freed of and used for the future memory allocation.? what would be the output?
You are not supposed to free any addresses but those returned by
malloc(),calloc()orrealloc(). Andp + 20is no such address.http://codepad.org/FMr3dvnq shows you that such a
free()is likely to fail.Does the pointer passed to free() have to point to beginning of the memory block, or can it point to the interior? is also worth reading.
Even if you could use
free()on any pointer that points to a malloc’d memory – your could would free it twice since you are callingfree()on more than one memory inside that area. And double-frees are evil as they can result in security holes.