#include <stdio.h> #include <stdlib.h> #include <iostream> int main() { char* s = (char*)malloc(sizeof(char) * 3); //I allocate memory for 3 chars s[0] = 'a'; s[1] = 'b'; s[2] = '\0'; s[3] = 'd'; //This shouldn't work std::cout << s[3] << std::endl; //It prints out d, why? free(s); return 0; }
Why am I allowed to write s [3]?
Usually the malloc function allocates a certain minimum number of bytes, for example 16, even if you ask to select only one (or 3 as in your example) byte (s).
However, you should not rely on such a function function. An implementation is defined as malloc allocates memory. So your code has undefined behavior.
This is called undefined behavior.
The compiler does not prevent you from committing illegal actions; however, compiled code may not do what you expect.
s [100], . , , , .
, C/++ , . , , . , , Valgrind, cppcheck , . , cppcheck , valgrind .
, . , , .
d, , . undefined.
d
s [3]?
.
undefined, , .
s[3] = 'd'; undefined. , -, , .
s[3] = 'd';
. , . , . undefined.
, ...
, C: C , , . - . ( ), , .
, . , C , , , . , malloc - , . , , . : malloc ( ) ( ).
malloc