Why you *have* to understand memory constraints

People tend to avoid learning about memory. It’s almost impossible in C,… but C lets you do things that other languages won’t have a bar of. You can’t assume that all things are possible. In languages such as Ada, the program will throw an exception if memory constraints are violated. Take for example the following simple piece of Ada code:

with Ada.Text_IO; use Ada.Text_IO;
with ada.Integer_Text_IO; use Ada.Integer_Text_IO;

procedure primes is
    n : integer;
    primeNumbers : array(0..integer'last) of integer;

    put_line("Number of primes? ");
end primes;

It compiles okay, but when run, produces the following message:

raised CONSTRAINT_ERROR : erroneous memory access

Why? Print out the value of integer’last = 2147483647. Stacks only have so much memory, and aren’t bottomless. To get a better message, compile the program with  -fstack-check. Next time the program is run it produces the following error:

raised STORAGE_ERROR : stack overflow

This says it all. Over 2 billion elements is too much for a static array stored in the stack. It could be fixed by increasing the stack size, OR using dynamic memory. But more likely it could be fixed by not creating an array that large. Too many programmers assume resources are infinite, and they aren’t.  Even C doesn’t allow an array with 2147483647 elements in it – it’s just too large to store on the stack, and will result in a “Segmentation fault: 11” runtime error.

When data gets that big in most languages, you have to think beyond the stack and go dynamic.



Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.