Permalink
Browse files

Test when malloc fails

  • Loading branch information...
1 parent 8beeefc commit 7bc1329b31fb68fcba561a21b8dec61767a2801a @joshuaclayton committed Aug 28, 2010
Showing with 15 additions and 2 deletions.
  1. +3 −1 ext/sieve/sieve.c
  2. +4 −0 features/sieve.feature
  3. +8 −1 features/step_definitions/sieve_steps.rb
View
@@ -14,7 +14,9 @@ static VALUE sieve(const VALUE self) {
long number = rb_num2long(self) + 1,
* numbers = malloc(number * sizeof(long));
- if(numbers == NULL) { return Qnil; }
+ if(numbers == NULL) {
+ rb_raise(rb_eNoMemError, "Can't allocate enough memory.");
+ }
long i;
for(i = 0; i < number; i++) {
View
@@ -23,6 +23,10 @@ Feature: Sieve of Eratosthenes
| 30 | 2,3,5,7,11,13,17,19,23,29 |
| 110 | 2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109 |
+ Scenario: Allocating memory for the sieve raises an exception if it fails
+ When I run a sieve on 1000000000000000000
+ Then a NoMemoryError should be raised
+
Scenario: Prime tables
When I load all the primes from "features/support/primes.txt"
And I run a sieve on the last number
@@ -1,5 +1,8 @@
When /^I run a sieve on (\-?\d+)$/ do |number|
- @result = number.to_i.sieve
+ begin
+ @result = number.to_i.sieve
+ rescue Exception => @sieve_exception
+ end
end
Then /^I should have the primes (.*)$/ do |primes|
@@ -27,6 +30,10 @@
Then %{I should have the primes #{prime_file_process(path).join(",")}}
end
+Then /^a NoMemoryError should be raised$/ do
+ @sieve_exception.should be_a(NoMemoryError)
+end
+
module PrimeFileProcessor
def prime_file_process(path)
File.new(path).read.strip.split(/\s+/).map(&:to_i)

0 comments on commit 7bc1329

Please sign in to comment.