Abdullah
Abdullah

Reputation: 541

Dynamic array confusion

I was just brushing up my C concepts a bit where I got confused about some behavior. Consider the following code snippet:

#include<stdio.h>
#include<stdlib.h>

int main (){


    int * arr;
    arr= malloc(3*sizeof(*arr));
    arr[0]=1;
    arr[1]=2;
    arr[2]=3;
    arr[3]=4;
    printf("value is %d \n", arr[3]);

return 0;


}

The problem is that the program functions correctly! As far as I understand I allocate memory for an array of 3 integers. So basically when I try to put a value in arr[3] there should be a segmentation fault as no memory has been assigned for it. But it works fine and prints the value 4. Either this is some weird behavior or I seriously need to revise basic C. Please if anyone can offer some explanation I would highly appreciate it. Thanks.

Upvotes: 4

Views: 124

Answers (4)

Benedict Cohen
Benedict Cohen

Reputation: 11920

Here's my guess based on my understanding of how memory is allocated (it may be wrong - so vote it down if it is!):

The address of arr[3] is in a memory page that your app has permission to write to. I think 4KB is a common page size. The malloc call resulted in 1 page being mapped to your app, of which you're only using the first 3*sizeof(*arr) bytes, therefore there is space left after arr[2] which your app has permission to write to, but malloc has yet to issue. If you were to perform another malloc the returned address will be bigger than arr and may equal the address of arr[3].

Upvotes: 2

Levon
Levon

Reputation: 143047

You could get a segmentation fault at any time, you got "lucky" this time. This is undefined behavior, so you might get a seg fault some other time.

C does not do any bounds checking, so while e.g., Java would have complained, C is quite happy to do whatever you ask it to do, even to the program's own detriment.

This is both one of its major strengths, and also weaknesses.

Upvotes: 6

NPE
NPE

Reputation: 500257

Your program has undefined behaviour. This does not mean that it is guaranteed to segfault. The failure might manifest itself in other ways (or not at all).

Upvotes: 3

Alok Save
Alok Save

Reputation: 206518

Technically, It is Undefined Behavior, Which means anything can happen not necessarily a segmentation fault.
Just your program is not a valid program and you should not write invalid programs and expect valid /invalid behaviors from them.

Upvotes: 10

Related Questions