0

I know that the malloc, allocate the contigous blocks of memory and return the first address of the allocation, which we keep in a pointer an use it.

I have the following question:

I discovered that if I allocate a number of bytes less than necessary or if try to access something which exceeds the bytes allocated the program still work.

int *ptr;
ptr = (int*)malloc(sizeof(int) * 2);
*ptr = 1;
*(ptr + 1) = 2;
*(ptr + 2) = 3;

After my mind, *(ptr + 2) = 3; should not work but it still work. I think because *(ptr + 1) is followed by *(ptr + 2) in memory.

My question is why it work and if it work like this why we don't use malloc for allocate only the first element of anything?

Xtx
  • 83
  • 10
  • 4
    undefined behaviour. that's all. it works, .... or not – Jean-François Fabre Aug 16 '17 at 21:19
  • The behavior of your code is undefined. When you assign value, it may work but could be corrupted next time you use this location. You may be corrupting a particular location after just writing on it as well – MCG Aug 16 '17 at 21:24
  • 1
    UB is like shooting in the small room. Ricochets may kill or injure you, but nothing my happen as well – 0___________ Aug 16 '17 at 21:31
  • depends on memory management in your kernel. If `malloc` returns a valid pointer, then your kernel has allocated _at least_ the amount of memory you requested; it could potentially allocate more. However, you certainly cannot and should not count on that behavior; accessing beyond your chunk of memory is UB. – yano Aug 16 '17 at 21:38
  • Xtx What do you expect to have happened with `*(ptr + 2) = 3;`? – chux - Reinstate Monica Aug 16 '17 at 21:41
  • 1
    @chux Maybe got segmentation fault or an other error. – Xtx Aug 16 '17 at 21:45
  • Try `free()`ing that pointer - you may get the crash you expected. –  Aug 16 '17 at 21:48
  • 1
    @Xtx That is the deal about C, when code breaks various rules, the language is not _specified_ to catch the transgression. Code is on its own: [no training wheels](https://i.ytimg.com/vi/2unTOA4bw-M/hqdefault.jpg). – chux - Reinstate Monica Aug 16 '17 at 21:52

1 Answers1

0

Malloc and free function as parts of a memory manager. They help you manage memory use, so your program does not accidentally overlap data in the same memory space. Your program typically has access to the entire writable memory space (This is OS and language dependent) at all times. Malloc and Free help you keep track of which memory you are currently using. When you call malloc, you are requesting a block of free memory from the memory manager. It returns to you a pointer to the start of that memory block (and you know where it ends, because you requested the size), and assures you that additional calls to malloc will not return that same memory until that block has been freed. It is up to you to make sure that your program does not write outside of the memory space you allocate, and that you free any memory you allocate.

MEHM-
  • 98
  • 5