views:

209

answers:

3
+2  Q: 

Why the SIGSEGV?

Why is this code throwing up a SIGSEGV:

int main()
{
    unsigned long toshuffle[9765625];

    unsigned long i;

    for (i=0; i< 1000; i++)
        toshuffle[i]= i;

    return 0;
}

Pointers will be appreciated. (No Pun intended :))

+7  A: 

Probably because you can't allocate 9765625 longs on stack (what is this site called again? :)). Use malloc() instead.

Lukáš Lalinský
make that `9765625*sizeof(long)` bytes
laalto
Oops, right. For some reason I read they are chars.
Lukáš Lalinský
Thanks both of you.
Amit
+14  A: 

Use malloc() to get that much memory. You're overflowing the stack.

unsigned long *toshuffle = malloc(9765625 * sizeof(unsigned long));

Of course when you're done with it, you'll need to free() it.

NOTE: In C++, you need to cast the pointer to the correct type.

Jurily
"Overflowing the stack", it finally has been said! :)))
o_O Tync
Don't cast malloc() in C. It hides errors if you've forgotten to include stdlib.h (it is needed for C++ though, I think).
paxdiablo
Indeed. void * does not cast automatically in C++.
Jurily
in C++ you would be doing new long[9765625], and wouldn't bother with neither casts nor sizeof... :)
roe
how to make the compiler to report an error when the stack size is exceeded.
iamrohitbanga
Thanks Jurily, I should have thought about Stack size and Heap size. But, now I know.
Amit
@iamrohitbanga: At compile time, which is where the compiler works, you do not have an idea about the Stack size that is available to you.
Amit
@Amit is right but it's worse than that. The compiler has *no* idea how big the stack is, it just generates the instructions. The linker *does* know the stack size but has no idea how your code will use it. That means you have to fail at runtime.
paxdiablo
+2  A: 

From the manpage

  • RLIMIT_STACK

The maximum size of the process stack, in bytes. Upon reaching this limit, a SIGSEGV signal is generated. To handle this signal, a process must employ an alternate signal stack (sigaltstack(2)).

Amigable Clark Kant