You only allocated memory for one int
:
x = malloc(sizeof(int)); // malloc allocates a memory chunk to only hold one int object.
Indexing x
at x[i] = i+1;
or y
at printf("%d ", y[i]);
in the loops with anything other than a value of 0
for i
(like x[0]
or y[0]
) invokes undefined behavior because you would attempt to write to and read from not allocated memory.
"then this means if I don't have any enough buffer, it also will give a segmentation fault for i < 4
?"
Exactly. You know that is the bad thing on undefined behavior. It does not need to provide wrong results or errors. So, the i < 4
code is broken, too.
Since you written to "only" 12 bytes after the allocated memory (since sizeof(int)
common is 4
), it might have worked because there was no other necessary information in memory thereafter, but your code is absolutely broken nonetheless.