159

I am trying to write a C program in linux that having sqrt of the argument, Here's the code:

#include<stdlib.h>
#include<stdio.h>
#include<math.h>

int main(char *argv[]){
    float k;
    printf("this is consumer\n");
    k=(float)sqrt(atoi(argv[1]));
    printf("%s\n",k);
    return 0;
}

After I type in my input at the "shell> " prompt, gcc gives me the following error:

Segmentation fault (core dumped)
Natan Streppel
  • 5,759
  • 6
  • 35
  • 43
Farzaneh Torkpichlou
  • 2,306
  • 3
  • 14
  • 18

1 Answers1

180

"Segmentation fault" means that you tried to access memory that you do not have access to.

The first problem is with your arguments of main. The main function should be int main(int argc, char *argv[]), and you should check that argc is at least 2 before accessing argv[1].

Also, since you're passing in a float to printf (which, by the way, gets converted to a double when passing to printf), you should use the %f format specifier. The %s format specifier is for strings ('\0'-terminated character arrays).

Eric Finn
  • 8,629
  • 3
  • 33
  • 42
  • 3
    I was taught that it should be `int main(int argc, char** argv)` instead of `int main(int argc, char *argv[])`. Though the way you put it is correct,` char\*\*` is the actual 'correct' way to do it because it represents a pointer to a pointer to a character. – Willothy Jul 13 '17 at 22:44
  • 13
    @WillHopkins The standard says that `int main(void)` and `int main(int argc, char *argv[])` or equivalent are acceptable, with the footnote after "equivalent" saying " Thus, `int` can be replaced by a typedef name defined as `int`, or the type of `argv` can be written as `char ** argv`, and so on." So really, it's a matter of style. (see 5.1.2.2.1 Program startup) – Eric Finn Jul 13 '17 at 22:52
  • 2
    Yeah, I just thought I'd mention it because that's what I use:) – Willothy Jul 13 '17 at 22:54
  • Could you please develop a bit more "and you should check that argc is at least 2 before accessing argv[1]" to help me understand what it means? Thanks! – Ni-Ar Aug 18 '21 at 10:22
  • 1
    @Ni-Ar `argc` is how many values are in `argv`. So before you do anything with `argv[1]`, you need to ensure `argc >= 2` – Eric Finn Aug 19 '21 at 13:34