Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 767
Abdullah Avatar asked Nov 29 '22 14:11

Abdullah


2 Answers

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.

like image 87
Alok Save Avatar answered Dec 05 '22 02:12

Alok Save


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.

like image 39
Levon Avatar answered Dec 05 '22 03:12

Levon