(hopefully)simple question

Paul Dow CRI-UK paul at sequoia.cray.com
Sat Apr 6 03:03:19 AEST 1991


In article <1991Apr5.132443.7726 at linus.mitre.org>, shaula at maestro.mitre.org (Shaula Doyle) writes:
|> related declrations from top;
|> struct timeval wait;
|> struct timeval * wait_ptr;
|> timeout is parameter, earlier write statement showed to be 10.
|> 
|> 1  if (TRACE)printf("read and except masks set\n");
|> 2  if (timeout < 0) wait_ptr = 0;  /* set timeout characteristics */
|> 3  else {
|> 4	  wait.tv_sec = timeout;   /* 0 is immediate return */
|> 5	  *wait_ptr = wait;
|> 6	}
|> 7  if(TRACE)printf("timeout set to %d\n",timeout);
|> 
|> A bus error came between the two trace statements on the _second_
|> iteration of the loop in which this was enclosed.
|> I changed line 5 from
|> 	*wait_ptr = wait;
|> to
|> 	wait_ptr = &wait;
|> 
|> and that fixed it.  My question is: why?  what was wrong?  I know
|> that a segmentation error means I tried to write outside my program
|> address space, can someone give me an explanation of what a bus 
|> error is?  I hope this isn't considered a waste of time, this seemed
|> to me the kind of esoteric C question this group would like.
|> FYI: I'm using cc under SunOS 4.1.1
|> 
|> -thanks for the time- shaula
|> 
|> PS I regularly program in about 3 different languages, and I find
|> I get confused on basic syntax sometimes.  K&R seems to make a 
|> horrible reference for this sort of simple detail, and I was 
|> hoping someone could recommend a good alternative?  thanx again.
|> shaula at maestro.mitre.org

Without the whole of the code it is difficult to fully analyse the problem,
but from the fragment above, line 5 looks very suspicious.

*wait_ptr = wait

is going to copy the wait struct to wherever wait_ptr is pointing to.  The question is - where is it pointing to.  It appears to be uninitialised, hence
a random address is being referenced - et voila - bus error/segmentation violation.

I presume that wait_ptr is being passed to a select(2) call or equivalent,
in which case the corection to line 5 woule be correct, i.e. 

wait_ptr = &wait

sets the pointer variable wait_ptr to point to the wait data sructure.  This
can be viewed as assigning the address of wait to wait_ptr.  Have a think about
what is being assigned where.

I would also be careful of using the name "wait" since this is also the name
of a Unix system call -- I've seen this macro'd before (as a quick & dirty hack).


Paul.



More information about the Comp.lang.c mailing list