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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With