What happens when the input length is longer than 2^31? You used an "int" for the length (also, why ever use a signed value for length?) --- even on LP64, that counter wraps at ~32 bits.
(Same question applies to how you handle the max_memory computation).
(Same question applies to how you handle the max_memory computation).