What mechanism detects access to unallocated memory?

From time to time I will have a "one by one" error, for example:

unsigned int* x = calloc(2000, sizeof(unsigned int)); printf("%d", x[2000]); 

I went beyond the selection, so I get an EXC_BAD_ACCESS signal at runtime. My question is: how is this detected? It seems like it will just silently return the garbage, since I'm only one byte, and not, say, a full page. What part of the system is stopping me from simply returning the garbage drum to x + 2000 ?

+4
source share
2 answers

The memory system has sentinel values โ€‹โ€‹at the beginning and end of its memory fields outside the bytes you have allocated. When you free memory, it checks to see if these values โ€‹โ€‹exist. If not, it tells you.

+1
source

Perhaps you are just lucky because you are using 2000 as the size. Depending on the size of the int total size is divided by 32 or 64 , so the chances are high that the end of it really stops the "real" distribution. Try with an odd number of bytes (better use a char array for this) and see if your systems are detected.

In any case, you should not rely on finding these errors this way. Always use valgrind or similarly to check access to your memory.

0
source

Source: https://habr.com/ru/post/1385606/


All Articles