I'm just learning C++ from the basics and in arrays learnt that in C++, there is no bound checking on arrays (Ex: int data[10], accessing data[12] compiler doesn't produce any error and give value in runtime if memory can be accessed)
I noticed the following difference when practicing int and char arrays:
char char_data[10];//char array case
char_data[1] = 'h';
char_data[15] = 'v';//line 1
char_data[11] = '\0';//line 2
int int_data[10];//int array case
int_data[1] = 10;
int_data[15] = 150;//line 3
int_data[11] = 0;//line 4
When I run the above code in main
with MSVC++ 14.0 , the code is compiled fine (as no bound checking in C++) but in char array case
, the code is crashing/breaking at line 2
where I equate the element to '\0'
(Its not considering the index but the value('\0'
) when the index is out of range) and the assembly produced is as follows:
10: data[15] = 'v'; //(no bound check here)
00CF1FE5 B8 01 00 00 00 mov eax,1
00CF1FEA 6B C8 0F imul ecx,eax,0Fh
00CF1FED C6 44 0D EC 76 mov byte ptr data[ecx],76h
11: data[11] = '\0';//line 2 (bound check here)
00AF1FFA 89 8D F0 FE FF FF mov dword ptr [ebp-110h],ecx
00AF2000 83 BD F0 FE FF FF 0A cmp dword ptr [ebp-110h],0Ah
00AF2007 73 02 jae main+5Bh (0AF200Bh)
00AF2009 EB 05 jmp main+60h (0AF2010h)
00AF200B E8 6C F1 FF FF call ___report_rangecheckfailure (0AF117Ch)
00AF2010 8B 95 F0 FE FF FF mov edx,dword ptr [ebp-110h]
00AF2016 C6 44 15 EC 00 mov byte ptr data[edx],0
Here, if the value is other than '\0'
, there is no assembly generated for rangecheck failure
. But if I consider the case of int, its not checking the range when the value for an out of range indexis 0
('\0'
is nothing but 0
). I couldn't understand this behavior.
Is this a compiler dependent or this behavior (bound check if value is \0
) is same across all the compilers?
Please help!!!