简体   繁体   English

c fscanf for int导致段错误

[英]c fscanf for ints causes segfault

DISCLOSURE: This is homework. 披露:这是家庭作业。

The code below is meant to read a command file formatted like: 以下代码旨在读取格式如下的命令文件:

ADD 6 6 5
ADDTERM 0 1 1
MULTIPLY 2 40

and call the appropriate command using the given parameters. 并使用给定的参数调用适当的命令。 For some reason, while ADD and ADDTERM work as expected, I get a segfault when the multiply line is read. 由于某种原因,虽然ADD和ADDTERM可以按预期工作,但在读取乘法行时却出现了段错误。

    int arg_1 = 0, arg_2 = 0, arg_3 = 0;

    while(fscanf(commands, "%s", command) != EOF)
    {
            if(strcmp(command, "ADDTERM") == 0)
            {
                    /*The following line runs fine!*/
                    fscanf(commands, "%d %d %d",
                                    &arg_1, &arg_2, &arg_3);
                    printf("ADDTERM, Poly: %d, Coeff: %d, Exp: %d\n",
                                    arg_1, arg_2, arg_3);
                    if(polys[arg_1] == NULL)
                    {polys[arg_1] = CreatePolynomial();}
                    AddTermToPoly(polys[arg_1], arg_2, arg_3);
            }

            else if(strcmp(command, "MULTIPLY") == 0)
            {
                    /*The following line results in a segfault*/
                    fscanf(commands, "%d %d", &arg_1, &arg_2);

                    printf("MULTIPLY, Poly: %d, Multiplier: %d\n",
                                    arg_1, arg_2);
                    MultiplyPoly(polys[arg_1], arg_2);
            }

            /*...*/  
   }

This is also only a problem on my school's Linux server. 这也是我学校的Linux服务器上的唯一问题。 My home computer runs it just fine, using "gcc version 4.4.5 (Ubuntu/Linaro 4.4.4-14ubuntu5)", whereas my school uses "gcc version 4.1.2 20080704 (Red Hat 4.1.2-48)" 我的家用计算机使用“ gcc版本4.4.5(Ubuntu / Linaro 4.4.4-14ubuntu5)”运行得很好,而我的学校使用“ gcc版本4.1.2 20080704(Red Hat 4.1.2-48)”

Any ideas why this would be? 任何想法为什么会这样? Your help is appreciated! 感谢您的帮助!

You need to leave room for a null terminus '\\0' in your string. 您需要为字符串中的空终端“ \\ 0”留出空间。 You were okay with ADDTERM because it has 1 less letter than MULTIPLY. 您对ADDTERM没问题,因为它的字母比MULTIPLY少1个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM