I cannot see anything wrong with this.
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
/* Reference:
    (0 offset) uint32_t size;
    (+4 offset) uint32_t elementSize;
    (+8 offset) uint32_t lastIndex;
    (+12 offset) void* data
*/
void* create_pinned_array(uint32_t elementSize, uint32_t numberOfElements, size_t sizeOfData, void* data)
{
    uint32_t size = sizeOfData + 12;
    void* memory = malloc(size);
    memset(memory, size, 4); // size
    memset(memory + 4, elementSize, 4); // elementSize
    memset(memory + 8, numberOfElements-1, 4); // lastIndex
    memcpy(memory + 12, data, sizeOfData); // actual data
    return memory;
}
int main(void)
{
    int randomList[5] = { 1, 6, 2, 9, 8 };
    void* myIntegers = create_pinned_array(sizeof(int), 5, sizeof(randomList), randomList);
    FILE* testfp = fopen("testfile.bin", "wb");
    fwrite(myIntegers, sizeof(myIntegers), 1, testfp);
    fclose(testfp);
    free(myIntegers);
    return 0;
}
Each time I check with xxd, instead of an ordered binary file I am getting junk data which varies every time I execute the program.
 
     
     
    