Date: Fri, 11 Jun 2010 14:56:29 -0500 From: Dan Nelson <dnelson@allantgroup.com> To: Vikash Badal <Vikash.Badal@is.co.za> Cc: "freebsd-questions@freebsd.org" <freebsd-questions@freebsd.org> Subject: Re: threads and malloc/free on freebsd 8.0 Message-ID: <20100611195628.GB36450@dan.emsphone.com> In-Reply-To: <9B425C841283E0418B1825D40CBCFA613D9E3CA643@ZABRYSVISEXMBX1.af.didata.local> References: <9B425C841283E0418B1825D40CBCFA613D9E3CA643@ZABRYSVISEXMBX1.af.didata.local>
next in thread | previous in thread | raw e-mail | index | archive | help
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:
http://lists.freebsd.org/pipermail/freebsd-questions/2010-May/216652.html
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
later.
--
Dan Nelson
dnelson@allantgroup.com
Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?20100611195628.GB36450>
