Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

When I try to run this I get a segmentation fault:

#define FILE_NAME "test.html"
#define STRING_ARRAY_SIZE 1000000

int main() {
fstream file;
string line = "";
string string_array [STRING_ARRAY_SIZE];
int i = 0;

file.open(FILE_NAME);
while(getline(file, line)) {
    string_array[i] = line;
    i++;
    cout << line << endl;
}

file.close();
}

Instead, when I try to compile this, it works:

#define FILE_NAME "test.html"
#define STRING_ARRAY_SIZE 100000

int main() {
fstream file;
string line = "";
string string_array [STRING_ARRAY_SIZE];
int i = 0;

file.open(FILE_NAME);
while(getline(file, line)) {
    string_array[i] = line;
    i++;
    cout << line << endl;
}

file.close();
}

Turns out, the only difference is the size of the array. Why does it work when it is 100000, and it does not when it is 1000000? What is the maximum size? Thank you.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
558 views
Welcome To Ask or Share your Answers For Others

1 Answer

The limit is system (not only hardware, but also software, notably operating system and runtime) specific. See also this question very similar to yours.

You should try hard to avoiding too big call stack frames. These days on desktop or server machines, I would recommend at most a few dozen kilobytes for the biggest call stack frames (and very often much less, i.e. hundreds of bytes) - notably for intermediate - non-leaf- or recursive functions. A typical system has a machine stack able to grow to a few megabytes (but on embedded microcontrollers, or inside the Linux kernel, it could be a few kilobytes!). With multi-threaded applications it should be a little less (since each thread has its own stack).

On Linux and Posix systems you can use the setrlimit(2) syscall with RLIMIT_STACK to lower (and perhaps sometimes to slightly increase) the stack limit. In your terminal with a bash shell, use the ulimit -s builtin.

The following GCC options could interest you: -fstack-usage, -Wframe-larger-than=, -fstack-split

In your code, consider replacing

 string string_array [STRING_ARRAY_SIZE];

with

 vector<string> string_vector;

and replacing

string_array[i] = line;
i++;

with

string_vector.push_back(line);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...