what is Segmentation fault (core dumped)?

C

C Problem Overview


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)

C Solutions


Solution 1 - C

"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).

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionFarzaneh PichlouView Question on Stackoverflow
Solution 1 - CEric FinnView Answer on Stackoverflow