threads and malloc/free on freebsd 8.0

Dan Nelson dnelson at
Fri Jun 11 19:56:31 UTC 2010

In the last episode (Jun 11), Vikash Badal said:
> I have a thread socket application that seems to be behaving strangely
> In a worker thread, I have the following.
> <CODE>-----------
>    LogMessage(DEBUG_0, "allocated %ld", malloc_usable_size(inst));
>    free(inst);
>    LogMessage(DEBUG_0, "after free allocated %ld", malloc_usable_size(inst));
>    free(inst);
>     return 0;
> -----------</CODE>
> output> allocated 2304
> output> after free allocated 2304
> from playing around, this should have segfaulted but it didn't:
> if I try this from a non threaded, non socket code:
> <CODE>------------------
>    char *z;
>    z = (char*)malloc(1000);
>    printf("malloc is %ld\n", malloc_usable_size(z));
>    free(z);
>    printf("after malloc is %ld\n", malloc_usable_size(z));
> ------------------</CODE>
> Output> malloc is 1024
> Output> Segmentation fault (core dumped)
> Can anyone enlighten me ? why did the 2nd free not cause a segmentation
> fault ?

You asked this same question on May 24:

The answer is still the same:

 You're invoking undefined behaviour here by calling malloc_usable_size on a
 free'd pointer.  The function is free to crash, return useful data, or
 return useless data, at its discretion :)

The fix is to remove your second call to malloc_usable_size(z)).  Then
neither version will crash.  Also, a useful habit to start is to explicitly
zero the pointer you just free'd, to prevent it from being used accidentally

	Dan Nelson
	dnelson at

More information about the freebsd-questions mailing list