嵌套 for 循环中的分段错误
Segmentation fault in nested for loop
在我的应用程序中,我有一个包含程序配置的外部文本文件。我正在逐行读取该外部文件并将值添加到数组。在某些时候我必须基于数组嵌套循环来处理一些信息。下面是我的代码
#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 函数的值时,我得到了正确的值。
您似乎在重复使用 'a' 变量,这不是一个好主意,因为这样很容易出错。
但是,您的实际问题似乎是您调用 some_array[a].length()
作为 for 循环条件。如果 a 超出范围,这可能会导致分段错误。相反,使用 a < array_len
作为您的条件,其中 array_len 是数组的长度。
- 了解如何调试!在调试模式下构建和 运行 您的程序,并检查究竟出了什么问题。这是所有软件开发人员的一项关键技能。
- 确保您了解 for loop syntax
在我的应用程序中,我有一个包含程序配置的外部文本文件。我正在逐行读取该外部文件并将值添加到数组。在某些时候我必须基于数组嵌套循环来处理一些信息。下面是我的代码
#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 函数的值时,我得到了正确的值。
您似乎在重复使用 'a' 变量,这不是一个好主意,因为这样很容易出错。
但是,您的实际问题似乎是您调用 some_array[a].length()
作为 for 循环条件。如果 a 超出范围,这可能会导致分段错误。相反,使用 a < array_len
作为您的条件,其中 array_len 是数组的长度。
- 了解如何调试!在调试模式下构建和 运行 您的程序,并检查究竟出了什么问题。这是所有软件开发人员的一项关键技能。
- 确保您了解 for loop syntax