Afficher un message
Vieux 18/10/2007, 01h21   #2
Peter Pichler
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Re: Seg Fault - Can not access memory ?

[You really did not need to post your question 3 times. Your posts
may not appear immediately, that's just the way it is. You may need
to wait a bit.]

Mahendra Kumar Kutare wrote:

> I am trying to implement a webserver with boss-worker model thread
> pool implementation -


My first reaction was, "oh no, another off-topic question," but in
fact yours is perfectly topical.

<snip>

> /* Allocate a pool data structure */
> if ((threadpool = (threadpool_t) malloc(sizeof(struct threadpool))) ==
> NULL) {


In C, casting malloc is not required and may hide a problem.
the preferred way is 'type *p = malloc(*p);'. That way, even if type
changes, the statement will remain safe. In your case, you could do

if ((threadpool = malloc(sizeof(*threadpool))) == /*...*/

> perror("malloc");
> exit(1);
> }
>
> threadpool_add_work function has following code -
>
> if (threadpool->cur_queue_size == 0) {
> threadpool->queue_tail = threadpool->queue_head =workp;


What's workp? Is it initialized to a valid threadpool?

> printf("Signal for pthread_cond_wait waiting on
> queue_not_empty:: %d\n", threadpool->queue_not_empty);
> pthread_cond_signal(&threadpool->queue_not_empty);
> } else {
> (threadpool->queue_tail)-> next = workp;

^^^^^^^
Because if it isn't - BANG!

> threadpool->queue_tail = workp;
> }
>
> For the first HTTP request, it will find threadpool->cur_queue_size ==
> 0 and hence will execute the IF block of the above code, but for any
> subsequent request it will execute ELSE block above.
>
> When I am sending 2nd request, ITS SEGFAULTING at
> (threadpool->queue_tail)-> next = workp;
>
> I debugged it through gdb and when trying to print following -
>
> (threadpool->queue_tail)-> next
>
> it throws - Can not access memory


If it does, then the implementors obviously could not spell.
It should be "cannot" (one word).

> Which i believe is because - Memory is not allocated to the structure
> threadpool self element.


Not so much not allocated as not initialized, I believe.

> My Question is - When i allocate memory in the begining to threadpool
> structure do i have to still allocate memory for any element which is
> itself in this case. ? If so, how do i do that ?


I am not sure what you mean by "which is itself", but in general,
allocating alone leaves the value uninitialized. If the value happens
to be a struct, then its members are unitialized. Accessing an
uninitialized member may just yield garbage if it happens to be a
number, but if it is a pointer, the consequences may be more dire,
as you have experienced.

> Or is there something else which I am missing here ?


Probably initializing your workp. Since I do not know where it came
from, I cannot be sure.

Peter
  Réponse avec citation
 
Page generated in 0,07134 seconds with 9 queries