Im new there. I've wrote thread application at the first time. This is
simple HTTP "server" - actually this is HTTP "hello world" programm, Im
just reading request and all headers and writing same content in any
case... :) Can you please explain what is wrong with my code? The
problem is - seg faults of "hangs" in Linux and memory leaks (from
where???) in FreeBSD.
Alexander Voronin
> // This is server code
> void * theServer ( void * ss ) {
> // Getting parameters
> serverStatus *stat = ( serverStatus* ) ss;
...
> // Deleting parameter
> delete ( serverStatus* ) ss; // line 52
> printf ( "Server stopped.\n" );
>
> // Exiting
> pthread_exit(NULL);
> }
>
> // This function prepares data than run new thread with server
> void runServer ( int hand ) {
> serverStatus *ss = new serverStatus; // line 61
> if ( !ss ) {
> printf ( "Cant alocate memory for serverStatus\n" );
> close ( hand );
> } else {
> ss -> hand = hand;
> pthread_create( &ss->thread, NULL, theServer, ss ); // line 67
> }
> }
>
Does this Chaperon output explain it for you:
Writing to a dangling pointer.
Pointer : 0x0804fcb0
In block: 0x0804fcb0 thru 0x0804fcb7 (8 bytes)
block allocated at:
__builtin_new()
runServer() server.cc, 61
main() server.cc, 108
stack trace where memory was freed:
__builtin_delete()
theServer() server.cc, 52
pthread_start_thread()
Stack trace where the error occurred:
__pthread_create_2_1()
runServer() server.cc, 67
main() server.cc, 108
**Memory corrupted. Program may crash!!**
Think about what happens if the "handler thread" executes
to completion before the pthread_create() returns (and tries
to write thread-id into &ss->thread).
"C" programming errors such as this (and failure
to detach/join, etc) prompted me to write this:
http://www.terekhov.de/mythread.c
Any comments? What is wrong there? ;-) BTW, it's free.
regards,
alexander.