user1607425
user1607425

Reputation:

Segmentation fault on printing pointer value

The following program crashes when I try to print the value of v. I'm trying to understand why. Any suggestions?

#include <stdio.h>

int main() {

    int v[5000000];
    printf("\n\nv = %p", v);
     return 0;
}

EDIT: the program does not segfault if instead of allocating 5000000 elements I allocate 500000 or less.

EDIT(2): increasing the stack size solved the problem. On Linux, I increase the stack size after reading the answer of stephane-rouberol (using ulimit -s <some_large_number>).

Upvotes: 0

Views: 477

Answers (6)

Kiril Kirov
Kiril Kirov

Reputation: 38163

Congrats, you have stack overflow :)

Find a way to increase the size of the stack or just allocate the array dynamically:

int* v = malloc( 5000000 * sizeof *v);

/* do something */

free( v );

Upvotes: 1

Lundin
Lundin

Reputation: 213740

As others have said, stack overflow. To understand why and when the code actually crashes, this is what goes on between the lines:

  • Try to allocate 5000000 * sizeof(int) on the stack. Let's assume this is 20MB.
  • The compiler (as opposed to the linker) most likely doesn't know how large the stack is, so it merrily assumes that 20MB of the stack are taken.
  • When calling printf(), the pointer address is passed on the stack to the function. The compiler will try to push this pointer address (4 bytes) at stack location 0 + 20000004. This is outside valid memory and here the program will crash.
  • Had the compiler used another calling convention for printf(), for example by passing the pointer address in a CPU register instead, the program wouldn't have crashed, not until you actually tried to read/write from that huge array.

Upvotes: 0

Stephane Rouberol
Stephane Rouberol

Reputation: 4384

Stack overflow ! See ulimit -s if you use bash or limit stacksize if [t]csh

Or instead of using stack, you can use the heap with malloc

Upvotes: 1

Ed Heal
Ed Heal

Reputation: 59997

Try

printf("\n\nv = %p", (void *)v);

Upvotes: 0

AndersK
AndersK

Reputation: 36082

The stack size of a program is dependent on compiler switches and defaults are different from OS to OS. In your case it sounds as if the stack is too small to accomodate that large number. See your compiler(linker) switches to increase stack size.

Upvotes: 0

UmNyobe
UmNyobe

Reputation: 22890

You already have the cause. 5000000 is too big to handle for the program stack where v will be allocated. You should allocate it dynamically with malloc.

Upvotes: 0

Related Questions