小字符串数组赋值会导致分段错误
我的原始代码(如下)在大约 num_atoms=150,000 处的字符串数组分配处给出了段错误:
int num_atoms=dimension[0]*dimension[1]*dimension[2]*prim_lat.size();
double superlat[num_atoms][3];
string current_occ[num_atoms];
认为这是我遇到堆栈溢出问题的第一个实例,并认为您可以使用动态分配分配给堆,我尝试了:
int num_atoms=dimension[0]*dimension[1]*dimension[2]*prim_lat.size();
double superlat[num_atoms][3];
string *current_occ = new string[num_atoms];
此代码在 num_atoms=350,000 处出现段错误。我不确定这个问题的解决方法。这只是我需要增加堆栈/堆限制的情况吗?如果是这样,我可以将其作为 gcc 选项吗?
My original code (following) gives a seg fault at the string array assignment at about num_atoms=150,000:
int num_atoms=dimension[0]*dimension[1]*dimension[2]*prim_lat.size();
double superlat[num_atoms][3];
string current_occ[num_atoms];
Thinking this was a first instance of me hitting a stack overflow issue, and thinking you can assign to the heap using a dynamic allocation, I tried:
int num_atoms=dimension[0]*dimension[1]*dimension[2]*prim_lat.size();
double superlat[num_atoms][3];
string *current_occ = new string[num_atoms];
This code gave a seg fault at about num_atoms=350,000. I'm not sure the workaround for this issue. Is this just a case where I need to increase the stack/heap limit? If so, can I do this as a gcc option?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在第二个示例中,您仍然将
superlat
存储在堆栈上。您也可以将其移至堆中。这很可能就是导致问题的原因,因为在第一个示例中,您在堆栈上存储了 num_atoms x2 指针(每个
string
一个指针,每个double
一个指针 -数组),第二个你在堆栈上存储 num_atoms x1 指针(每个 double 数组只有一个),因此段错误之前的原子数量加倍。You're still storing
superlat
on the stack in your second example. You could move it over to the heap as well.Chances are this is what's causing the problem, since in the 1st example, you're soring num_atoms x2 pointers on the stack (one pointer per
string
, one pointer perdouble
-array) and in the second you're storing num_atoms x1 pointers on the stack (only one perdouble
-array), so the number of atoms before segfault doubled.