I use this method for doing malloc over a 2d array, my sources are
http://c-faq.com/aryptr/dynmuldimary.html and Modify malloc strategy for 2D Array so malloc succeeds:
int
main(int argc, char *argv[])
{
long **array = NULL;
array = malloc(5 * sizeof(long *));
for (int i = 0; i < 5; i++)
array[i] = malloc(3 * sizeof(long));
array[4][2] = 515;
array[4][3] = 212;
array[4][10000] = 3;
printf("%ld\n", array[4][10000]);
return 0;
}
My question is,
Why don’t I get a segmentation fault in the execution of any of the last three lines before the return? Is it safe (ignoring the inexistence of free)?
The operating system allocates memory to an application in pages (typically 4 KB). For efficiency, it is possible to use Huge Pages (e.g. 2 MB)
The first page 0 is never allocated and if you ever try to access it you get a segmentation fault. e.g. accessing any pointer from 0 – 4095 will get a segmentation fault on most systems.
However, once a page has been allocated to you, you can read and write any part of that page without a segmentation fault. (Code pages are usually protected from writes)
When you use malloc it makes sure that the pages you need are there. However you could just access the memory you have and change any way you like. (Assuming you knew how much that was)
Generally, this is more dangerous than useful, but it may help explain why accessing memory in an invalid way doesn’t guarantee a segmentation fault.
Note: malloc has a small structure e.g. 8 bytes, at the start of each allocated block of memory before the block itself, if you corrupt this then
mallocandfreewill not work correctly.