As i know the functions brk() , sbrk() are used for reallocating the memory.But how they are different from realloc() function ?.Give me the coding examples.
sbrk are system calls (implemented in the kernel) while
realloc are library functions in user space. So the
malloc etc functions use
sbrk internally but provide additional functionality (see man(2) for more details about
brk and man(3) for more details about
brk only tells the kernel how much memory your program wants to use, by giving the the kernel a pointer to the largest virtual memory location that your program may use. But you only have exactly one big chunk of memory.
malloc helps you to subdivide this huge block of memory into smaller parts.
Example code doesn't make much sense here, because
malloc work on different levels. But you could think how you would implement a very simple (and non-thread-safe) version of
free and where you would use
brkto increase the usable memory we got from the kernel
And as @BasileStarynkevitch remarked in his comment, as an alternative to
brk you could also use
flags=MAP_PRIVATE|MAP_ANONYMOUS) to reserve a single block of memory backed by the swap file. For details about mmap see man(2).
At the OS level (in the Unix model, at least), your program has one big region of memory for program text, initialized and uninitialized data, and the "heap", for dynamically-allocated data. (The stack is separate.) You can adjust the size of that region using
sbrk, but you can't rearrange it, and it's always contiguous. The vast majority of programs that do dynamic memory allocation require something more flexible.
realloc are C library functions that give you something more flexible. Underneath, they get memory from the OS by calling
sbrk, but then they do extra processing to let you allocate (a) any number of chunks of (b) different sizes and which you can (c) individually return to the pool when you're done with them and incidentally (d) resize.
But when you return memory to the pool with
free, it generally just goes back into the pool that future calls to
malloc by your program will draw from; memory is generally not given back to the OS.
(Sorry for not providing any example code; I don't have time for that just now.)