Expert C Programming

(Jeff_L) #1

if (p->name != NULL)


(void) printf("%s", p->name );


else


(void) printf("(null)");


In cases like this, however, the conditional operator can be used instead to simplify the code
and maintain locality of reference:


(void) printf("%s", p->name? p->name : "(null)");


A lot of people prefer not to use the —? — : — conditional operator, because they find it
confusing. The operator makes a whole lot more sense when compared with an if statement:


if (expression) statement-when-non-zero else statement-


when-zero


expression? expression-when-non-zero: expression-


when-zero


When looked at this way, the conditional operator is quite intuitive, and allows us to feel
happy with the one-liner instead of needlessly inflating the size of the code. But never nest
one conditional operator inside another, as it quickly becomes too hard to see what goes
with what.


Common immediate causes of segmentation fault:



  • dereferencing a pointer that doesn't contain a valid value

  • dereferencing a null pointer (often because the null pointer was returned from a system
    routine, and used without checking)

  • accessing something without the correct permission—for example, attempting to store a value
    into a read-only text segment would cause this error

  • running out of stack or heap space (virtual memory is huge but not infinite)


It's a little bit of an oversimplification, but for most architectures in most cases, a bus error means that
the CPU disliked something about that memory reference, while a segv means that the MMU disliked
something about it.


The common programming errors that (eventually) lead to something that gives a segmentation fault,
in order of occurrence, are:



  1. Bad pointer value errors: using a pointer before giving it a value, or passing a bad
    pointer to a library routine. (Don't be fooled by this one! If the debugger shows that
    the segv occurred in a system routine, it doesn't mean that the system caused it. The
    problem is still likely to be in your code.) The third common way to generate a bad
    pointer is to access something after it has been freed. You can amend your free
    statements to clear a pointer after freeing what it points to:



Free download pdf