CreatedById will be populated in a record only after insert operation.
Before insert, the CreatedById will be null.
In the is case, we can use UserInfo.getUserId() which returns the current User Id.
Check the below link for sample code
Cheers!!!