-1

I know that malloc(n) returns a pointer to a memory of n bytes. Let's say if I want 5 bytes of memory and initialize as an integer array (I know the insufficient number of bytes are allocated).

int *a = malloc(5);
*a = 1234;
*(a+1) = 5000;

printf("%d ",*a);
printf("%d",*(a+1));

As far as I know, the first four bytes are used by 1234 and the second element should have only one byte left. But, the output is1234 5000. How does the second element get the remaining 3 bytes?

Later if I uninitialize the array by free(a), does it free the additional bytes of the second element?

  • 1
    You have allocated five bytes. Assuming `int` is four bytes you write a total of eight bytes. That goes out of bounds of the allocated memory, and as mentioned elsewhere leads to *undefined behavior*. It's your responsibility as programmer to make sure your program does not have undefined behavior. – Some programmer dude Dec 17 '21 at 06:59
  • It is possible that the memory manager allocated memory in block sizes that guarantee alignment for any object. So for example the actual memory reserved might be 8 bytes, but only the 5 requested are guaranteed. Or perhaps the memory manager handles memory in 16-byte paragraphs. – Weather Vane Dec 17 '21 at 07:10
  • 1
    Did you try to free the memory? Some allocators put some magic bytes after the allocated blocks and complain if you free some memory that was messed up. – Gerhardh Dec 17 '21 at 07:17

3 Answers3

2

does malloc reserves the space or just returns the pointer to starting location?

malloc() does reserve the space and expects code to respect that space allocated. If you try to access more, you are on your own.

How does the second element get the remaining 3 bytes?

Undefined behavior (UB). Anything may happen. The rest of the code is irrelevant - maybe.

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
0

You "overwrite" the bytes that happen to be after the allocated bytes with your *(a+1)=. These bytes do not belong to you.
You are lucky that it did not crash because this is Undefined Behaviour.

Raildex
  • 3,406
  • 1
  • 18
  • 42
0

The compiler can optimize the code as it sees fit, and doesn't have to literally perform what is written. Just produce the intended result.

So, on my machine the compiler removes unneded reads and writes and transforms the code into

nt *a = malloc(5);

printf("%d ",1234);
printf("%d",5000);

and suddenly nothing is overwritten!

BoP
  • 2,310
  • 1
  • 15
  • 24