Malloc struct in one thread, free in another => SEGV

Sat Jul 19 11:32:00 GMT 2008

On 18 Jul 2008, Christopher Taylor outgrape:

> This is probably a pebkac issue and the workaround is obvious and
> works but I'm curious why this doesn't?
> The code below segv's at the indicated free.

Actually it doesn't compile. No headers, the definitions of
MAX_NUM_BUFFERS and MAX_BUFFER_SIZE are missing, and pthread_create()
has four parameters, not two (I presume NULL attrs and a routine of

With those fixes, it doesn't crash for me and valgrind likes it (tho'
I'm using glibc 2.7 here).

> Seems to me that malloc would keep track of an address and a size and
> what I do with those and what structures that I populate that space
> ?should be? irrelvant to malloc/free.  Either that's not the case or
> (more likely) I'm doing something that's out in left field.

I'd guess so, but I can't guess what that might be.

> The code below is a simplicicaton of what I've built on my debian etch machine:
> gcc version 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)
> libc6-dev  2.3.6.ds1-13etch5  GNU C Library: Development Libraries and
> Header Files
> NPTL 2.3.6

A compiling crashing testcase would be nice. A backtrace or valgrind
output (or both!) would be even nicer. :)

> If I free the memory in the thread it was created everything works.
> If instead of passing a prt to a struct, I pass an int .. everything works.

Which function are you talking about passing the pointer to a struct to?

> If I malloc the memory in chunks instead of all at once (the obvious
> workaround mentioned above) ... everything works
> Does anyone have any ideas?

Looks fine to me (modulo the fact that it doesn't compile). (You don't
need to cast the pointer passed to free() or returned from malloc(),
FWIW. void * is compatible with pointers to all object types.)

More information about the Libc-help mailing list