running int a strange scenario where malloc is allocating more memory than I ask for:
void function (int array [], int numberOfElements) {
int *secondArray = ma
You are just lucky. Malloc can and sometimes does ask from more memory off the OS - Taking into account paging. Sometimes it does not even need to ask the OS for memory as it has asked for extra earlier. Therefore the malloc could ask for a page of memory - more that enough to satisfy your request and the extra memory happens to be filled with zeros.
You are in the land of undefined behaviour. So all bets are off.
malloc
is actually allocating exactly the right amount.
However, you're accessing memory beyond the allocation.
What exists there is completely undefined and could really be anything.
In your case, it was one "junk" number and four zeroes.
/** its print 0 0 0 0 because in C no array bound if you define your array
* size is 4 but
* you want to store data more than array size you can store so you print your
* array.
* for(i = 0; i < numberOfElements; i++) its give data and 0 also because you
* store the data
* only 5 position but you print it max size so it give you 0 0 0
*/
int *secondArray = malloc(sizeof(int) * numberOfElements/2); // no matter either use it or
int *secondArray = malloc(sizeof(int));
// ^^^ this will take same memory