Search code examples
c++segmentation-faultnested-loopsifstream

Segmentation fault in nested for loop


In my application I have external text file which contain the configurations for my program. I'm reading that external file line by line and adding values to arrays. In some point I have to nested loop based on arrays to process some information. below is my code

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

                }
            } 

}

But when I run this I always get seg fault. But if I comment out the one loop it working perfectly fine. When I COUT the values on readconf function I'm getting the correct values.


Solution

  • It looks like you're reusing the 'a' variable, which isn't a good idea because it's very easy to make an error this way.

    However, your actual issue appears to be that you're calling some_array[a].length() as the for loop condition. If a is out of bounds, this could result in a segmentation fault. Instead, use a < array_len as your condition, where array_len is the length of the array.