To finish this chapter, here is another example of how you can access beyond the boundaries of an array [19] in unsafe codes. Study this program carefully – it should be self-explanatory.
[19] This is impossible in Java or safe C# codes, but could be done easily in C and C++ where array boundaries are not checked for the developer.
1: using System; 2: 3: class TestClass{ 4: 5: static string name = "c sharp"; 6: 7: unsafe static void PerformOp(char* p) { 8: int i; 9: 10: // will print out 'c sharp' (7 characters) 11: for (i=0; p[i]!=' '; i++) 12: Console.Write(p[i]); 13: 14: // will print out 13 more characters which 15: // are beyond the array boundaries. 16: for (int j=i; j<20; j++) 17: Console.Write(p[j]); 18: } 19: 20: unsafe static void Main() { 21: fixed (char* p = name) 22: PerformOp(p); 23: } 24: }
Output: [20]
[20] Output may differ depending on what is stored beyond your array's allocated space.
c sharp ?? A
3.142.174.85