New memory allocation for buffer

Yesterday when I started replacing some static buffers I realized that the memory allocation was too complicated and the probability of losing data on failures was too high. The new memory allocation is safer, data is preserved even in the event of failures and memory is used more carefully.
Printf now returns 0 to signal that we need to retry the last call and -1 when there is an error.