This simple method just creates an array of dynamic size n and initializes it with values 0 ... n-1. It contains a mistake, malloc() allocates just n instead of sizeof(int)
You allocate 8 bytes for the array, but you store 8 int
, each of which is at least 2 bytes (probably 4), so you are writing past the end of the allocated memory. Doing so invokes undefined behavior.
When you invoke undefined behavior, anything can happen. Your program can crash, it can show unexpected results, or it can appear to work properly. A seemingly unrelated change can change which of the above actions occur.
Fix the memory allocation, and you code will work as expected.
int *result = malloc(sizeof(int) * n);