Segmentation fault when free

Mel fbsd.questions at rachie.is-a-geek.net
Sun Sep 21 19:50:11 UTC 2008


On Sunday 21 September 2008 14:57:06 Nash Nipples wrote:
> > > can someone please explain to me what happens to the
> >
> > allocated memory
> >
> > > called within a function assigned to its local pointer
> >
> > after this function
> >
> > > ends
> >
> > Ok - let's see if I get this right:
> > - the allocated memory
> > - called within a function
> > - assigned to a local pointer
> >
> > Any malloc'ed memory is application global accessible.
> > Assigning a pointer to
> > a variable doesn't allocate memory (the compiler and
> > runtime libraries
> > already setup storage for the variable, at declaration
> > time). So, I have no
> > idea what you mean with the "called within a
> > function" part.
> >
> > --
> > Mel
>
> thanks for making it even more clear to me.
> actually what i meant was this:
>
> void function(void){
>   char *p;
>   p = malloc(1);
> }
> int main(void){
>   while (1){
>     function();
>     /* in the end of this function function()
>      * the memory is still allocated
>      * even when the only pointer who knows its address
>      * does not longer exist
>      * which is why we have to free() the memory
>      * during the application runtime
>      * to avoid it from growing to ridiculous size
>      */
>   }
> }

Right, this is one of the annoyances of C-programming "Who still knows where 
my pointer is". You can use a general rule though:
If I don't return this pointer, and I don't assign this pointer to a 
parameter, and I don't assign this pointer to a global variable, I should 
free this pointer myself.
(Yes yes, malloc'd static storage - new can of worms).
-- 
Mel

Problem with today's modular software: they start with the modules
    and never get to the software part.


More information about the freebsd-questions mailing list