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)
Whether printf()
allocates any memory in the course of performing its work is unspecified. It would not be surprising if any given implementation did so, but there is no reason to assume that it does. Moreover, if one implementation does, that says nothing about whether a different implementation does.
That you see different behavior when the printf()
is inside the loop tells you nothing. The program exhibits undefined behavior by overrunning the bounds of an allocated object. Once it does that, all subsequent behavior is undefined. You cannot reason about undefined behavior, at least not in terms of C semantics. The program has no C semantics once undefined behavior commences. That's what "undefined" means.