【问题标题】:Segmentation fault in nested for loop嵌套for循环中的分段错误
【发布时间】:2018-11-19 07:54:52
【问题描述】:

在我的应用程序中,我有一个包含我的程序配置的外部文本文件。我正在逐行读取该外部文件并将值添加到数组中。在某些时候,我必须基于数组嵌套循环来处理一些信息。下面是我的代码

#include <iostream>
#include <fstream>
#include <algorithm>

#include <stdlib.h>
#include <cstring>
#include <sys/stat.h>
#include <unistd.h>


using namespace std;

string ip_array[0];
string link_array[0];
string conn_array[0];

int readconf(){

    int ip_count = 0;
    int link_count = 0;
    int conn_count = 0;

    ifstream cFile ("net.conf");
    if (cFile.is_open())
    {
        string line;
        while(getline(cFile, line)){
            line.erase(remove_if(line.begin(), line.end(), ::isspace),
                                 line.end());
            if(line[0] == '#' || line.empty())
                continue;
            auto delimiterPos = line.find("=");
            auto name = line.substr(0, delimiterPos);
            auto value = line.substr(delimiterPos + 1);

                if ( name == "IP") {

                    //cout << value << endl;
                    ip_array[ip_count] = value;
                    ++ip_count;

                }
                else if ( name == "LINK") {

                    //cout << value << endl;
                    link_array[link_count] = value;
                    ++link_count;

                }
        }

    }
    else {
        cerr << "file read error.\n";
    }


}




int main()
{
    readconf();

        for( unsigned int a = 0; ip_array[a].length(); a = a + 1  ){

            cout << ip_array[a] << endl;

                for( unsigned int a = 0; link_array[a].length(); a = a + 1  ){

                    cout << link_array[a] << endl;

                }
            } 

}

但是当我运行它时,我总是遇到段错误。但是,如果我注释掉一个循环,它工作得很好。当我 COUT readconf 函数上的值时,我得到了正确的值。

【问题讨论】:

  • 在哪里发生崩溃?您是否尝试过使用调试器捕获它,并在代码中找到它发生的位置?此外,当使用调试器捕获崩溃时,调试器将允许您检查变量的值,以帮助您找出可能导致崩溃的原因。请了解如何做到这一点,或者至少编辑您的问题,向我们展示它在您的代码中发生的位置(以及所有相关变量的值)。
  • 您正在使用长度为零的数组。这意味着他们可以容纳零个项目。
  • 一个很大的提示是那些数组。数组及其大小在编译时是固定的,不能扩展。你需要开始了解std::vector
  • 另外,不要使用全局变量,这是一个坏习惯。也许您也应该学习课程?也许get a couple of good books 并正确学习 C++?

标签: c++ segmentation-fault nested-loops ifstream


【解决方案1】:

您似乎在重复使用“a”变量,这不是一个好主意,因为这样很容易出错。

但是,您的实际问题似乎是您调用 some_array[a].length() 作为 for 循环条件。如果 a 超出范围,则可能导致分段错误。相反,使用a &lt; array_len 作为条件,其中array_len 是数组的长度。

【讨论】:

    【解决方案2】:
    1. 学习如何调试!在调试模式下构建并运行您的程序,并检查到底出了什么问题。这是所有软件开发人员的一项关键技能。
    2. 确保您了解for loop syntax

    【讨论】:

      猜你喜欢
      • 2016-08-04
      • 2020-10-30
      • 2019-03-12
      • 2012-10-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-13
      • 1970-01-01
      相关资源
      最近更新 更多