[prog] Solution

Jimen Ching jching at flex.com
Sat Feb 1 08:25:31 EST 2003


On Fri, 31 Jan 2003, Sachin wrote:
>a small program which I had modularised.I just want you to tell me whether
>my approach of modularisation(separating header files and C source code,
>:--)  ) is correct.

Correct in the ANSI C sense, or correct in the 'programming style' sense?
In the ANSI C sense, my philosophy is, if it compiles... ;-)

For programming style, I prefer to only put code in header files when it
is absolutely necessary.  In your case, the "#include" of the socket
headers, i.e. net/inet.h, sys/socket.h, etc, should be in the .c file.
The reason is, if someone wants to call listener(), they don't need to
include sys/socket.h.  By placing the include directive in the header, you
force the caller of listener() to include sys/socket.h also.  This is not
a problem with small projects.  But with large projects and large header
files, it causes unnecesary compiler work.

In my personal programming style, I only put 'public' interfaces in
headers.  Everything else goes into a .c/.cpp source file.  You'll know
what is a 'public' interface when the compiler complains.  With gcc, you
can use -Wall -Wstrict-prototypes.  Note, strict-prototypes is not enabled
by -Wall.

The second advantage of this style is that the global namespace is not
poluted with implementation specific symbols.

>Also,beyond the message "segmentation fault" ,I am not able to glean much
>information regarding the status of the program.

Have you tried using a debugger?  There are graphical frontends to gdb,
such as DDD and Insight (http://sources.redhat.com/insight/).  This is the
best way to find any software defects.

>I've also found that compiling with -Wall option saves a lot of headache

Yes.  Don't forget the -Wstrict-prototypes one as well.  Of course, if you
compile C code with a C++ compiler, you'll get even better warnings.  A
lot of people use C++ in this way.  Note, -Wstrict-prototypes is a C only
option to gcc.  C++ uses strict prototypes by design.

>but I still get the problem even when the program contains no dynamically
>allocated memory(which is considered a main source of Segmentation
>fault).Can anyone elaborate what are the potential bugs for the
>generation of segmentation fault.

Segmentation faults are the result of memory corruption.  It doesn't
matter whether the memory is from the heap, the stack or static (global).
Memory is memory.  The best way to track down the cause is to use a
debugger.

--jc
-- 
Jimen Ching (WH6BRR)      jching at flex.com     wh6brr at uhm.ampr.org



More information about the Programming mailing list