karthik
karthik

Reputation: 355

Dynamic memory allocation in C

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?

Upvotes: 1

Views: 536

Answers (2)

ThiefMaster
ThiefMaster

Reputation: 318488

You are not supposed to free any addresses but those returned by malloc(), calloc() or realloc(). And p + 20 is no such address. http://codepad.org/FMr3dvnq shows you that such a free() is likely to fail.

The free() function frees the memory space pointed to by ptr, which must have been returned by a previous call to malloc(), calloc() or realloc(). Otherwise, or if free(ptr) has already been called before, undefined behavior occurs. If ptr is NULL, no operation is performed.

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 calling free() on more than one memory inside that area. And double-frees are evil as they can result in security holes.

Upvotes: 10

Alok Save
Alok Save

Reputation: 206508

It will result in Undefined Behavior.

The free() function shall cause the space pointed to by ptr to be deallocated; that is, made available for further allocation. If ptr is a null pointer, no action shall occur. Otherwise, if the argument does not match a pointer earlier returned by the calloc(), malloc(), posix_memalign(), realloc(), strdup() function, or if the space has been deallocated by a call to free() or realloc(), the behavior is undefined.

Upvotes: 2

Related Questions