Is python buffer overflow proof?

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Sun Aug 2 17:18:27 CEST 2009


On Sun, 02 Aug 2009 13:50:14 +0000, Jizzai wrote:

> Is a _pure_ python program buffer overflow proof?

It's supposed to be.
 
> For example in C++ you can declare a char[9] to hold user input. If the
> user inputs 10+ chars a buffer overflow occurs.
>
> In python, I cannot seem to find a way to define/restrict a string
> length. This is probably by design and raises the topic in question.

That's a separate issue from being buffer overflow proof. You can't 
specify that a string have a maximum of N characters except by slicing 
the string after it's formed:

s = "x"*10000  # Make a big string.
s = s[:100]  # Limit it to 100 characters.

But Python won't overflow any buffers even if you try to create a truly 
huge string:

s = "x"*(1024**4)  # Try to create a 1 TB string.

Your PC will run slow while Python and the OS tries to allocate 1TB of 
memory, then it will safely raise MemoryError. Pure Python should never 
dump core.



-- 
Steven



More information about the Python-list mailing list