Program received signal SIGSEGV, Segmentation fault error

你离开我真会死。 提交于 2019-12-25 07:28:54

问题


Program received signal SIGSEGV, Segmentation fault

on LINE : if (argv[1][0] == '-').

I was trying to make it do something when sees '-c' flag in unix shell

int main(int argc, char **argv)
    {

    int target_column=1;
    int column_flag=0;
    int descending_flag=0;

    /* command-line argument control */
        printf("Argument(s) detected(%d)\n", argc);

        /* default mode */
        if (argc = 3)
        {
    if (argv[1][0] == '-')
             {
                 /* column flag */
                 if (argv[1][1] == 'c')
                 {
                     column_flag=1;
                     printf("column flag found, ");
                 }
                 /* error checking */
                 else
                 {
                     fprintf(stderr, "tsort -c <column> [-d]\n");
                     exit(EXIT_FAILURE);
                 }
             }

Much Appreciate your answers. It was definitely that small typo.


回答1:


If you want to check for the number of the arguments use ==:

if (argc = 3)   // This assigns 3 to argc and always yields true
{
    if (argv[1][0] == '-')

should be

if (argc == 3)
{
    if (argv[1][0] == '-')

Compiler should warn you about this. If not, always compile with -Wall -Wextra to avoid this.




回答2:


You have a typo in your code:

if (argc = 3)

should rather be:

if (argc == 3)

.

People often put the constant on the left to avoid such type of an error, for example:

if(3 = argc)

would not compile because a constant cannot be assigned to.




回答3:


You change the value of argc to 3 on this line:

if (argc = 3)

It should be:

if (argc == 3)

This works (the compiler doesn't give an error message) because assignment has a return value in C++. In this case that value is 3, which evaluates to true. Therefore, you will always try to access the first argument looking for '-', which might not exist. This leads to a segfault.



来源:https://stackoverflow.com/questions/18934642/program-received-signal-sigsegv-segmentation-fault-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!