Segmentation fault due to lack of memory in C
This code gives me segmentation fault about 1/2 of the time:
int main(int argc, char **argv)开发者_StackOverflow中文版 {
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
You are overflowing the default maximum stack size, which is 8 MB.
You can either increase the stack size - eg. for 32 MB:
ulimit -s 32767
... or you can switch to allocation with malloc
:
float *test = malloc(2619560 * sizeof test[0]);
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 it static
instead:
static float test[2619560];
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 of main
it makes little difference (other than the mostly theoretical possibility of a recursive main
).
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.
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".
精彩评论