Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
571 views
in Technique[技术] by (71.8m points)

c++ - Maximum size of local array variable

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

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...