Q:

How is free work?

0

How is free work?

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Answer:

When we call the memory management functions (malloc, calloc or realloc) then these functions keep extra bytes for bookkeeping. Whenever we call the free function and pass the pointer that is pointing to allocated memory, the free function gets the bookkeeping information and release the allocated memory. Anyhow if you or your program change the value of the pointer that is pointing to the allocated address, the calling of the free function gives the undefined result.

Let us see a program to understand the above concept. The behavior of the below program is not defined.

#include <stdio.h>
#include <stdlib.h>
int main()
{
    char *pcBuffer = NULL;
    //Allocate the memory
    pcBuffer  =  malloc(sizeof(char) *  16);
    //make sure piBuffer is valid or not
    if (pcBuffer == NULL)
    {
        // allocation failed, exit from the program
        fprintf(stderr, "Out of memory!\n");
        exit(1);
    }
    //Increment the pointer
    pcBuffer++;
    //Call free function to release the allocated memory
    free(pcBuffer);
    return 0;
}

OutPut: Undefined Result

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

What is a dangling pointer?... >>
<< What is dynamic memory fragmentation?...