Pranav said:
I am trying to allocate memory using sbrk() and when I try to free the
allocated memory at the end of the code using free(), gives me a
segmentation fault when I try to execute the code., How to free memory
exactly?
free() can only free memory obtained from malloc(). You almost
certainly want to be using malloc() to get memory instead of sbrk().
sbrk() is a lower-level, Unix-specific function, and one of its
disadvantages is that you usually can't reliably free memory allocated
with it, and certainly not via the free() function.
<off-topic>
sbrk() comes from a time when the usual memory model for Unix programs
was a single, contiguous chunk of memory. The address of the end of
this chunk was called the "break point". sbrk(n) would ask the
operating system to allocate enough memory to advance the break point by
n bytes. This is how malloc() would get additional memory. Some
systems allowed you to move the break point backwards by passing a
negative number to sbrk(), thus returning memory to the system, but this
required that *all* the memory beyond the new break point was no longer
needed. If your memory needs didn't occur in just the right order, this
usually didn't happen. This is why traditional implementations of
free() didn't actually return memory to the OS, but only reserved it for
future malloc() calls.
Nowadays the mmap()/munmap() calls allow a program to get memory from
the OS in a discontiguous fashion, so it is easier to return it later.
If for some reason you need something lower-level than malloc, mmap is
probably the way to go; you can map /dev/zero or use a flag to request
an anonymous mapping not associated with a file. Further discussion
about this would be better directed to comp.unix.programmer.
</off-topic>