yoon
yoon

Reputation: 1385

Why one 2-d array cause seg-fault, and another do not?

There are several ways to define 2-d array.

And I found out that when defining an array using the code below:

int arr[2][2];
cout << arr[3][3];

this doesn't result in seg-fault. This just prints some dummy value.

On the other hand,

int** arr = new int*[2];
for(int i = 0; i < 2; i++) arr[i] = new int[2];
cout << arr[3][3];

this results in seg-fault.

What's the difference between these?

Upvotes: 0

Views: 39

Answers (3)

Nathanael Demacon
Nathanael Demacon

Reputation: 1217

Static arrays are located in the stack so it can't segfault since the program CAN access its own stack. However you could segfault a static array if you go out of range of the stack.

A dynamic array (pointer) on the other hand is located in the heap. So by going out of range you ask to get a pointer outside your program's dedicated memory emplacements which result in a segfault.

This is called an Undefined behavior.

Upvotes: 1

Jesper Juhl
Jesper Juhl

Reputation: 31467

Reading uninitialised values is Undefined Behaviour. Your program is invalid (both variants) and has no meaning when you do that and any behaviour is allowed. The compiler is literally allowed to do anything. You cannot reason about a program containing UB, don't even try.

Upvotes: 3

Max Vollmer
Max Vollmer

Reputation: 8598

You have undefined behavior. Anything can happen. There is no use in speculating why you get these results.

That said, this is likely what's going on:

The first is a continuous block of memory (2*2*sizeof(int)) on your stack, where arr[3][3] means read data from 3*3*sizeof(int) bytes after the start of that block.

The other is one block of memory (2*sizeof(int*)) on the heap containing two pointers pointing at two separate blocks of memory on the heap (each 2*sizeof(int)), where arr[3][3] means read data from 3*sizeof(int*) bytes after that first block of memory, interpret whatever you find there as a memory address, and then read data from 3*sizeof(int) bytes after that address.

Upvotes: 0

Related Questions