Re: Segmentation error with c program

Go to solution
Henry Chua
Super Advisor

Segmentation error with c program

Hi guys,

I a writing a c program. but whenever try to run the file without arguments it will give segmentation. How can I catch this error before it terminate the progam. Thanks.

Best regards
Honored Contributor

Re: Segmentation error with c program

"Segmentation violation" means your program is trying to access memory outside the areas reserved to it. With C programs, this usually means you've made some sort of error with pointer variables.

You should check the number of command line arguments (int argc) before trying to read the argument strings (char **argv).

The argv is an 1-dimensional array of pointers to strings (1-dimensional arrays of characters): its type can be expressed equivalently as "char **argv", "char *argv[]" or "char argv[][]". I wouldn't recommend the last form though, because it easily leads you to think in the wrong way: argv definitely isn't a two-dimensional array, although it may seem somewhat like it.

Normally, when you run a program without arguments, argc is usually 1. It means you'll have the name that was used to start the program in *argv[0]. If argc is equal to 1, you must not try to access *argv[1], because argv[1] is either NULL or random nonsense and trying to dereference either of those will produce the error message you're getting.

In some special situations, the program can be started with argc equal to 0. Never just assume that you can read *argv[0] without checking the value of argc first.