Turbo C help wanted

ejs at orawest.ARPA ejs at orawest.ARPA
Tue Oct 11 04:02:19 AEST 1988


In article <3ef69894.14927 at asterix.engin.umich.edu> yilin at caen.engin.umich.edu (Zhao) writes:
    >	[code elided]
    >          temp = (TREEPTR)calloc(1, sizeof(TREENODE));
    >          if (!temp) /* If out of memory, should be reported here! */
    >              printf("calloc error: empty pointer created!\n");
    >          temp->num = info.num;
    >	[code elided]
    >	       return(temp);
    >	[code elided]
    >
    >... "Null pointer assignment" only appears when we use EXIT(0)
    >instead of RETURN or when Version 1.5 is used. ...
    >I can list all of nodes just before program termination.
    >If there is a null pointer assigned, 
    >can we print out the whole linked list?
    >
    >Yilin Zhao
    >yilin at caen.engin.umich.edu

Mr. Zhao:
  In your code above, when calloc returns null, and your test succeeds,
printf is called. Execution continues, however, to dereference this NULL
pointer, and you get the runtime error you describe. Your confusion over
the lack of error message may possibly be explained by the fact that on
many systems, unflushed i/o buffers are not necessarily flushed when
termination of a process results from a runtime error. You do in fact
call printf, but you don't necessarily see the message. If you call
exit, however, in some systems a cleanup routine is called to flush
buffers, etc., before exiting. This may explain why you get different
behavior when you call exit.

  In general, code like that you posted is terribly useful-- if you
detect an abnormal situation that will likely cause an abormal
termination due to a runtime error, then most likely you would want to
force a normal termination upon detection, in order to ensure correct
reportage of the detection.

  So, most of the time one doesn't see
	if (!good) printf("error");
but instead
	if (!good) {
	    printf("error");
	    exit(0);
	}
and in fact 
	    fprintf(stderr, "error");
is even better since stderr should be unbuffered.
If you are really paranoid, you may do a 
	    setbuf(stderr, (char *)0);
or equivalent call in main() before any other i/o;
this should ensure that stderr is unbuffered, and each
character written on it will appear in its destination as
soon as possible.

John Sebes
Odyssey Research Associates, West



More information about the Comp.lang.c mailing list