I'm working on OS X. I've written a simple code like
pTest = (char*)malloc(sizeof(char) * 3);
pTest[0] = 0;
pTest[1] = 1;
pTest[2] = 2;
pTest = (char*)realloc(pTest, sizeof(char) * 2);
printf("%d %d %d %d\n", pTest[0], pTest[1], pTest[2], pTest[3]);
pTest[3] = 100; // memory access violation.
If this code does not cause access violation, Why does realloc need? Although we are allocated memory in the heap segment with a small size, all we have to do is access to a further index such as pTest[100]
, pTest[2048]
, and pTest[65536]
.
Could someone explain why does not cause access violation?