Jeremy Smith
Jeremy Smith

Reputation: 15069

Why is my C extension not creating unique instances?

I created a C extension, the purpose of which is to determine if a series of cards will result in a straight or not. The example might be a little more complicated than necessary to show the issue, but essentially foo should be storing inside of it all the cards that were evaluated (each with an assigned index). So bar should have an entirely separate set of cards and indexes. But it seems that when I start assigning cards to bar, it is overwriting foo. I'll include my code below in case I am doing something wrong with pointers.

>> require 'ext/straight_count' #=> true                                                                                            

>> foo = EV::StraightCount.new; 
>> foo.evaluate(6,0); 
>> foo.evaluate(5,1); 
>> foo.evaluate(4,2); 
>> foo.evaluate(3,3); 
>> foo.evaluate(3,4); 
>> foo.evaluate(3,5); 
>> foo.evaluate(3,6); 
>> foo.straight_cards
=> []

>> bar = EV::StraightCount.new; 
>> bar.evaluate(11,0); 
>> bar.evaluate(10,1); 
>> bar.evaluate(9,2); 
>> bar.evaluate(8,3); 
>> bar.evaluate(7,4); 
>> bar.evaluate(2,5); 
>> bar.evaluate(2,6); 
>> bar.straight_cards
=> [11, 10, 9, 8, 7]

>> foo.evaluate(3,6); 
>> foo.straight_cards 
=> [11, 10, 9, 8, 7]

.h file

static int *pCards;
static int *pSortedCards[NUM_CARDS];
static int i, rMadeHandIndex, cCards[NUM_CARDS], begin_straight, end_straight;

VALUE rIsFound = Qfalse;

static VALUE EV, StraightCount;

static void reset_score();
static VALUE found();
static VALUE score();
static VALUE straight_cards();

Upvotes: 1

Views: 88

Answers (1)

Arafangion
Arafangion

Reputation: 11910

pSortedCards appears to be a global. Hence the reason why you have shared state.

Upvotes: 4

Related Questions