C 内存不足导致分段错误
这段代码大约有 1/2 的时间给我带来分段错误:
int main(int argc, char **argv) {
float test[2619560];
int i;
for(i = 0; i < 2619560; i++)
test[i] = 1.0f;
}
我实际上需要分配一个更大的数组,是否有某种方法可以让操作系统允许我获得更多内存?
我使用的是 Linux Ubuntu 9.10
This code gives me segmentation fault about 1/2 of the time:
int main(int argc, char **argv) {
float test[2619560];
int i;
for(i = 0; i < 2619560; i++)
test[i] = 1.0f;
}
I actually need to allocate a much larger array, is there some way of allowing the operating system to allow me get more memory?
I am using Linux Ubuntu 9.10
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您溢出了默认的最大堆栈大小,即 8 MB。
您可以增加堆栈大小 - 例如。对于 32 MB:
...或者您可以切换到使用
malloc
进行分配:You are overflowing the default maximum stack size, which is 8 MB.
You can either increase the stack size - eg. for 32 MB:
... or you can switch to allocation with
malloc
:现在,您正在堆栈上分配(或至少尝试)
2619560*sizeof(float)
字节。至少在大多数典型情况下,堆栈只能使用有限的内存。您可以尝试将其定义为static
:这会将其从堆栈中取出,因此它通常可以使用任何可用内存。在其他函数中,将某些内容定义为
static
会改变语义,但在main
的情况下,它几乎没有什么区别(除了递归main的大多数理论上的可能性) )。
Right now you're allocating (or at least trying to)
2619560*sizeof(float)
bytes on the stack. At least in most typical cases, the stack can use only a limited amount of memory. You might try defining itstatic
instead:This gets it out of the stack, so it can typically use any available memory instead. In other functions, defining something as
static
changes the semantics, but in the case ofmain
it makes little difference (other than the mostly theoretical possibility of a recursivemain
).不要将这么大的对象放入堆栈中。相反,请考虑通过使用 malloc() 或其朋友进行分配,将其存储在堆中。
2.6M 浮点数并不算多,即使在 32 位系统上,地址空间也应该没问题。
如果您需要分配非常大的数组,请务必使用 64 位系统(假设您有足够的内存!)。 32 位系统每个进程只能寻址大约 3G,即使如此,您也无法将其全部分配为单个连续块。
Don't put such a large object on the stack. Instead, consider storing it in the heap, by allocation with malloc() or its friends.
2.6M floats isn't that many, and even on a 32-bit system you should be ok for address space.
If you need to allocate a very large array, be sure to use a 64-bit system (assuming you have enough memory!). 32-bit systems can only address about 3G per process, and even then you can't allocate it all as a single contigous block.
这是堆栈溢出。
您最好使用 malloc 函数来获取大于堆栈大小的内存,您可以从“ulimit -s”获取它。
It is the stack overflower.
You'd better to use malloc function to get memory larger than stack size which you can get it from "ulimit -s".