【问题标题】:Segmentation fault using linux command lines in c++在 C++ 中使用 linux 命令行的分段错误
【发布时间】:2017-09-12 21:46:46
【问题描述】:

当我运行命令行 ./hello.out 时,内核被转储。谁能告诉我我错过了什么。

#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
int counter = 1, sum = 0,x;
x= atoi(argv[1]);
if (x<0)
{cout << "Error\n"; exit(1);}
if (argc !=2)
{cout << "Error\n"; exit(1);}

while (counter <= x)
    {
            cout << counter << endl;
            sum = sum + counter;
            ++counter;
    }
cout << "Sum is " << sum << endl;

return 0;
}

【问题讨论】:

  • 如果argv[1] 不存在,程序将崩溃,因为您试图读取一个不存在的值。您需要使用至少一个参数调用它,或者进行一些错误检查。例如:./hello.out 5 例如,您可以在尝试调用 atoi(n) 之前将其放在线路上:if (argc &lt; 2) return -1;
  • 而且从来没有任何借口可以使用 atoi()。
  • 我们更喜欢术语“未定义的行为”而不是“崩溃”,因为它不会总是崩溃。它可能会以一种更安静、更阴险的方式搞砸,在为时已晚之前没人注意到。
  • 抱歉,未定义的行为在这里当然是合适的术语。谢谢!
  • “我错过了什么?” - 了解what the arguments to main() mean,以及如何使用它们。

标签: c++ segmentation-fault


【解决方案1】:

您似乎正在尝试访问不存在的argv 元素,因此您正在访问您的程序无法控制的内存。当您这样做时,内核将立即终止您的程序。您正在检查argc 的值,这是正确的做法,但您是在访问argv 之后才这样做的。您只需在访问 argv 之前执行该检查。

#include <iostream>
using namespace std;      

int main(int argc, char *argv[])
{
    int counter = 1, sum = 0,x;

    if (argc !=2) argv    // <-- Make sure there are two elements before indexing into
    {
        cout << "Error\n";
        exit(1);
    }
    x = atoi(argv[1]);    // <-- You should study and use 'std::stoi' instead
    if ( x < 0 )      
    {
        cout << "Error\n";
        exit(1);
    }

    while (counter <= x)
    {
        cout << counter << endl;
        sum = sum + counter;
        ++counter;
    }
    cout << "Sum is " << sum << endl;

    return 0;
}

【讨论】:

    【解决方案2】:

    嗯....在第 6 行您访问 argv[1] 但您还没有通过任何参数...所以 argv[1] 可以指向任何地方

    【讨论】:

      猜你喜欢
      • 2014-03-22
      • 1970-01-01
      • 1970-01-01
      • 2021-03-29
      • 2020-09-16
      • 1970-01-01
      • 1970-01-01
      • 2016-06-12
      • 1970-01-01
      相关资源
      最近更新 更多