The answer to the OP's question is yes, size_t is most appropriate for the example code, where no pointer values are being subtracted from each other, and there are no cross-compiler/library compatibility issues around malloc
behaviors. Regardless of difference in heap managers, in C, an array can be SIZE_MAX
bytes in length and that requires a size_t
to represent it. Nothing in the standard requires a heap manager to be able to allocate all of a process memory space in the heap, or to allocate up to SIZE_MAX
bytes for that matter, but an array can be SIZE_MAX
in length, hence size_t
is appropriate.
Even if n
is signed, using a ptrdiff_t
for i
isn't going to help, as the initial i < n
test will fail anyway, if n
is negative, because i
is initialized to zero. There is no index into i
that a size_t
index cannot access. The only place that ptrdiff_t
is needed, is where you subtract one pointer value from another, and the OP isn't asking about that.