嵌套for循环中的分段错误

时间:2018-11-19 07:54:53

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

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

#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;

                }
            } 

}

但是运行此命令时,我总是会遇到段错误。但是,如果我注释掉一个循环,它就可以正常工作。当我关闭readconf函数的值时,我得到了正确的值。

我用来获取数据的配置文件就是这样

IP=8.8.8.8
IP=8.8.4.4
LINK=main
LINK=backup

如何解决此问题

2 个答案:

答案 0 :(得分:1)

您似乎正在重用'a'变量,但这不是一个好主意,因为这样很容易出错。

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

答案 1 :(得分:0)

  1. 学习如何调试!以调试模式生成并运行程序,并检查出了什么问题。这是所有软件开发人员的一项关键技能。
  2. 确保您了解for loop syntax
相关问题