Thready McParallel: the patron devil of programming

Afair while back, I had a call from someone who wanted to know if I could fit in some consultancy time to help solve some development problems. It turned out to be the least profitable work that I have ever done. I had an immediate hunch and after just five minutes on the blower to their programmer it was problem solved. Honestly, I am really, really shit at capitalism.

They were developing a client-server game for the web and had a terrible capacity issue with the server: one connection was good, two was OK but unreliable but above three and it was unusable. Given that they were aiming for many thousands, this was clearly not good and they were desperately worried: they had interfaced correctly with the server software that they had licensed in and couldn’t figure out what was going on.

Snake In Threads

Mr Snake here is wearing some nifty threads. His idea of threads, though, is somewhat different to mine

The server software that they had selected worked like you might expect: it handled connections, sending of data backwards and forwards over the Internet and dealt with disconnections. All they had to do was tie into a callback that would fire every time something happened. They then processed whatever it was and returned back to the server software. Simples, right? Nope. The server software had to be able to deal with many thousands of connections and lots and lots of stuff going on at unpredictable times so, as is appropriate, it was heavily multi-threaded. It had a “pool” of threads that handled receiving data from clients over the Internet. When data was received, the user specified callback was fired with a note to say “hey, I received this data from this person, so deal with it, sucker!”. Since the thread from the pool owned that data, it waited until the callback finished before freeing the memory and returning to a listening state. So, any guesses yet?
There’s a LOT more of this article…

Posted in Software development | Tagged , , , , , , , , | 2 Comments

PlayBook: Hahahahaha!

iToast

Friendly toast won't be smiling when you start eating him alive. How COULD you?

What do you know the BlackBerry chaps for? What’s that? As industry leaders in secure mobile e-mail solutions you say? Absolutely. So, if YOU were RIM and you were releasing a tablet computer thingie to compete with the iPad, what one feature would you make sure was a) present and b) industry leading? E-mail perhaps? A contacts application to go with it, maybe? No, those in charge have decided not to bother with an e-mail client or a contacts application for the time being because, after all, they’re just not important in a tablet device. Amazingly, their co-CEO managed to say this with a straight face shortly before riding off into the sunset on a magic unicorn:

“This is superior, it’s far more portable, it’s lighter in your hands, you can hold it for longer.” [Bloomberg]

Well, so’s this delicious mini-bakewell tart that I’m holding right now but it also can’t do e-mail.

To be fair, the PlayBook does do e-mail if it is tethered to a BlackBerry, but then my router browses the web when tethered to a computer and I can run at 80 miles an hour when tethered to my car.

Honestly, it’s absolutely hysterical watching so called innovators trip over themselves to make bad copies of Apple’s iPad. It’s like car-crash television without the car crash. Or the television. The catch-up approach to forging ahead is always going to leave you behind and not in a sexy surprise cuddle opportunity sort of way. If these guys and those at Samsung are the best that the competition can come up with then frankly, Apple could ship a touch sensitive piece of toast and still be market leaders. Hmmmmmm, toast… munch munch munch.

(PS: They also didn’t feel a calendar application was useful, so skipped that too.)

Posted in Miscellaneous rubbish | Tagged , , | 1 Comment

Tweet, twooo!

Artifical Owl

- Do you like our owl?
Is it artificial?
- Of course it is.
Must be expensive.
- Very...

So I have joined the social media revolution now by signing up to Twitter. Apparently the average age of Twitter users is now 40 so I figure I am ripe and ready. Now you, yes, you, can keep up with the mundane details of the Cobras Cobras life including such future classics like “I am on the train” and “I am in the toilet doing some important paperwork”. The Cobra family has embraced micro-blogging as another exciting way of reaching absolutely nobody with their tweets and twoots.

I had hoped to be ‘cobrascobras’ but someone has already taken that. It is outrageous, I mean, who on earth registers a Twitter name like ‘cobrascobras’? Except me, obviously. So I chose @pretzelsnake instead. He represents a rattlesnake curled up like a pretzel basking in the warm, sprummer sun.

Of course, I have ABSOLUTELY NO IDEA what I am doing. I think a retweet is when someone else thinks the rubbish I post is interesting enough to bore their followers with, I am pretty sure a hashtag doesn’t mean what I first thought it does and the @ thingies are our usernames and targets for tweeting to… perhaps. As well as having not even the smallest clue as to what it all means, I also am having a tough time explaining why I did it or what I hope to gain. Still, there’s nothing like charging into something new to illustrate how old and out of touch I am.

I have to say, though, the toughest challenge might be to say things in 140 characters. In the meanwhile, be gentle with me, this is like moving from a gramophone to MP3s.

Rattlerattlerattle.

Posted in Miscellaneous rubbish | Tagged , , , , | 6 Comments

That’s no moon!

Darth Giraffe

How is Darth Giraffe holding his light sabre? We may never know...

Itook my umbrella to London the other day in order to prevent it from raining. It was Mrs Cobra’s idea, she reminded me that Murphy’s Law means that if I don’t take it, I will end up more drenched than a drowning kitten. Likewise, in order to raise the temperature a few degrees I had the foresight to wear my winter jacket. Basically, I HAVE THE POWER! Muuuhahahahaha! Using nothing but the power of my mind, I molded the weather to sheer perfection. What is it that makes us believe that our actions affect the universe around us like that? Why should the presence of MY umbrella change the weather? What about the OTHER guy on the train who forgot his umbrella? Will an angry looking mini-cloud follow him around all day soaking him to the bones each time he steps outside?

We all seem to move through our lives believing that the force is strong in us: jumping in the bath will make the postman turn up with the parcel, ordering another pint will result in the delayed flight suddenly being “last call”, organising a BBQ will ensure that the hot weather breaks and the garden get watered, shaking the dice in a particular way will make a difference in the results… and it was that last one, the dice roll, that really got me thinking. I read a blog post where a chap called Juuso asked if he was a rational person for, as he put it, ‘putting effort’ into rolling a dice. I made a couple of comments but the whole thing vexed me (in a Khaaaaaaaaaaan! sort of way) for way too much time. I was chatting to some friends about the oddities in the brain that allowed us to believe that such rituals made any difference when one of them used a sentence involving the word ‘quantum’ – and we all know, when the word quantum is invoked, we’re all in deep trouble.

Let us take two silly examples. When I play Risk, Monopoly or Settlers of Catan I generally spend more time shaking the dice using my “secret method” than actually playing. And by “secret method” I mean just the right angles, length of time, chants and holding the cupped dice up to the side of my head just before finally rolling them. Needless to say, there is no statistical evidence to suggest that this works. Likewise, the time I invest gritting my teeth whilst shaking the scrabble letters bag… what the hell do I hope to achieve there? Am I hoping that the finer details of gravity will sort ‘heavy’ letters like M and W to the bottom whilst raising the ‘light’ ones like I and J to the top? Have I totally taken leave of my marbles? I am pretty sure I would have a cracking time explaining that to a shrink if I was stupid enough to ask one.

I potentially justified this by suggesting it is to do with the brain’s planning habit. We plan continuously: both forwards and backwards in time. After an event, for example, do you find yourself imagining how it might have turned out if you had done something different? Do you think “and if only I had said ‘and THAT was why the piano was missing it’s pedals’ it would have been brilliant”. Replaying and replaying events and imagining different outcomes to consider how one might approach it in the future appears to be normal. Then there is the future: considering the various outcomes of decisions that are about to be made. In the case of dice, though, the brain does not realise that such considerations are UTTERLY FUTILE

Or are they?

Do we actually possess The Force?

Were they the droids that we were looking for, after all?

Image credit Threepwood @ B3TA
"Those who are not shocked when they first come across quantum theory cannot possibly have understood it" -- Niels Bohr

Ok, so it is not with mitoclockweights or whatever that stuff is in Star Wars, but do we actually influence the outcome of events MERELY BY OBSERVING THEM? Is there something amazing going on at a quantum level that we do not yet understand? And even if there is, will that understanding ever lead to an ability to control it? Who knows, but there is much for us to learn: as Richard Feynman said in 1965, “I think I can safely say that nobody understands quantum mechanics” and I think I can safely say that this is true today. The problem with observation changing the outcomes is that it would appear to be impossible to observe what would happen without the observation.

We may not know about observational influence on our day to day lives now, but we will: it is a foolish man who bets against scientific progress based on today’s perceived limitations and impossibilities. Suggesting in the mid 50s that one day, you would be able to fit ten thousand transistors onto something the size of a fingernail would, at best, have got you laughed out of the room or more likely denounced as a witch or bundled into the back of a nondescript white van for transport to a “more comfortable location”. In the end, Intel was slapping 30 million of ’em onto something that size in 2001 and the latest and greatest exceed a billion. Those that believe something to be impossible in their lifetime should agree not to use it should it be invented. It would suck to be that person if the invention was teleporters, anti-gravity, faster-than-light travel or immortality, eh?

Anyway, I’m off to confuse storm troopers looking for droids and Darth Giraffe is disturbed by your lack of faith, young blogreader.

Posted in Miscellaneous rubbish | Tagged , , , , , | 8 Comments

Stop the universe, someone knows everything

You are not a fool just because you have done something foolish, only if the folly of it escapes you.

Ionce met a man who claimed to know everything about C++. Everything. Indeed, he was now looking for something that was more of a challenge for him. It is rare to get an opportunity to pick the brains of a genius level programmer so I thought I’d start by asking him what he thought of the proposed C++0x standard. Given that so much has changed and that the draft of the full standard consists of a 10MB PDF spanning one thousand and thirty four pages, imagine my surprise when after a paragraph of grade-a waffle, he only appeared to know anything substantial about one, relatively minor, feature: null_ptr.

Those of you who think that you know everything are annoying to those of us who do.”
– Possibly not words born from wisdom...

Crikey. I was so astonished to catch him out with such a trivial detail that my eyebrows raised to hitherto unknown heights. Given the fish in a barrel nature of further debate, I let my involuntary giggle finish itself, allowed my eyebrows to return to their usual latitude and then shuffled off to find someone at the party who wasn’t dangerously stupid.

Later on that evening, after much, much more wine, I accidentally got dragged into an argument with him after he gave some spectacularly bad advice to a Mac user who had made the mistake of asking him about backup solutions. Instead of answering “plug hard drive in, start Time Machine” he started his self-righteous sentence with “first, get a proper computer running Linux”. Unwelcome, I barged in anyway and was arguing about GIMP’s unsuitability for my level of artistry in minutes, but that’s another story. As to who looked more stupid in the end, I think it was a joint win: let’s face it, nothing is sadder than watching two drunk nerds arguing with each other about operating systems. Needless to say, the entire evening was not filed under “proudest moments”.

Rattle Trumpet

My own trumpet, yesterday

I don’t like to blow my own trumpet, but I reckon I am pretty good at C++. I have been using it for a very, very long time now and prior to that had a decade invested in C. However, even after a complete bottle of wine and an overly generous brandy to finish up with, I wouldn’t claim to know everything or indeed remotely close to everything. I learn more about programming in general, software architecture and the details of programming specific languages on a continuous basis and I LOVE it. Learning new ways to do cool things is one of the sheer joys of software development. Putting together all those commands and making the computer do something amazing is why I first started noodling around on my Dad’s computer back at the start of the 80s.

People who think that their knowledge is encyclopedic are incredibly dangerous. They are the sort of people who destroy the lives of others and then fuck off into the sunset blaming everyone else except themselves. They leave a trail of unfinished, ill considered works behind them that the real professionals have to fix. They fail to realise that knowledge is a moving target and feel that no one can possibly teach them something that they do not already know. You may know someone like this in your organisation. If so, run, run for the hills.

It is OK, indeed desirable, to have strong opinions. After all, if you are a yes-man, you will never finish anything as it will continually morph towards other people’s contradicting goals and never reach any of them. However, demonstrating once again that life is a soup of grey areas, the art to being open minded is knowing when to open your mind’s door and when to pretend to be out. People with a thirst to learn refine this throughout their lives but are smart enough to recognise that perfection can never be achieved, it can merely be approached to varying degrees of accuracy.

Posted in Software development | Tagged , , , | 1 Comment

Even the bees are wearing shades

British people are famous for talking about the weather. There is a good reason for this: we get an awful lot of it. We regularly get at least three seasons in one day, sometimes as many as six (sprummer is one of my personal favourites). Because of this, when it comes to nice weather we tend to live for the moment and that means having A BBQ NOW, not planning for one at the weekend when it will probably be frosty, stormy, typhoony or volcanoey. Even a couple of hundred miles away on the continent, the weather is often identical for days – if not weeks. Their weather forecast could simply say “pretty much the same as yesterday” and be accurate 95% of the time. Here in the UK, we would be bloody chuffed if the weather forecast could be accurate even half the time. But, although the evidence so far would suggest otherwise, I can’t complain:

Sprummer

Normally, no-one likes a showoff. But for this, Spring, we're prepared to make an exception

As Mrs Cobras’ wonderful picture shows, spring has been delightful and garden activities have gone from breaking the ice on the pond to basking in the sun in the space of a week. I would say that I hope the weather is good for you, too, but to be honest, I’m being really rather selfish about this.

Posted in Miscellaneous rubbish | Tagged , , , | 2 Comments

Mon aéroglisseur est plein d’anguilles

Hovercraft full of eels

Eels! They're so cute!

And yours might be too, so you should get it checked. The perils of not knowing even the most basic structural components of a foreign language are considerably more embarrassing than eel related confusion.

There I was, standing on the platform at the station minding my own business and reading the paper. The train was moments away and I’d cleverly positioned myself exactly not where the large group of schoolgirls, their luggage and their teachers were. If the train hadn’t decided to be four carriages long as opposed to the eight I was expecting, I’d not have had to walk the few extra yards that positioned me in the same carriage as them.

It turned out that they were on the way to Paris on Eurostar. You’d assume that given that this was a cultural visit to support their French lessons that they’d have accumulated some knowledge of the language by now – they were, after all, teenagers. Given that I would describe my fluency as “hahahahahahahahahaha!”, the fact that I was in a position to correct them whilst they practiced supported my theory that the way languages are taught in schools is fundamentally flawed.

And thus begins a surprisingly long, even for the Cobras, polemic on bad teaching along with an introduction to the future tense…
Continue reading

Posted in Learning French slowly | Tagged , , , , , , | 5 Comments

Beware the schedules of March

Unfinished code

A small amount of the vast fields of my unfinished code, yesterday

Well, polish my tabletops, March has passed away and April has sprung into action. Birds are nesting, trees are flowering and it is almost time to empty the lake of winter-detritus from the BBQ and fire it up for a good old fashioned drunken cooking session involving FIRE!

It’s also a great time for a monthly update on the progress of my iPhone game. Executive summary: grim. Here are the scores on the doors in handy tear-off table form:

Estimated total project duration: 4 months with a month’s contingency
Start date: March 2010 (yes, 2010)
Total progress so far: Three weeks (15%)
Total progress this month: Four hours (0.5%)
Estimated completion date: Mid 2025

Well, lookin’ good in at least one parallel universe. Fortunately, I have a good excuse: I have been incredibly busy doing actual work programming… you know, the stuff that pays the bills and all that jazzamatazz. I have also yet to officially find volunteers (or victims, depending on your perspective) to do the graphics, sound and level design (hint-hint, you know who you are). My plan for April and May is to knock out a simple level editor. With one of these, I can take my one level and knock out tons of them – it is the kind of thing I can do on the train and it will at least feel like progress.

Be sure to tune in for the April update, viewers, where we expect to be moving to rung 3 of a 400 rung ladder! Honestly, the excitement is killing me…

Posted in My iPhone game | Tagged , , , | 1 Comment

C-C-C-Cobra Breaker!

Bronx zoo's cobra, enjoying a quiet relaxing bask in the sun with his family

If you’re a fan of snakes, as I am, then you may have been following the Egyptian Cobra that made a successful bid for freedom from NYC’s Bronx Zoo. Said Cobra is now tweeting to throw people off the scent of his real mission and said zoo is basking in what very well could be a genius marketing move on their part. Obviously such a cobra-related issue is too much to miss, so I went out looking for him. Et voila! Le serpent! I interviewed him next to the pyramids in Egypt and he said: “Hissss beetle beetle bird bird hissssss bottle bird pyramid scribe beetle lion lion hisssss” which, roughly translated, means “I missed my family, so I came to visit them”. Ahhhhhhh! How cute!

I fear for his journey back to the zoo. Hopefully, the marketing gain from the international travels of Mr Cobra will prevent this story from ending badly… May the force be with you, little cobra, giant frightening humans can be incredibly stupid when it comes to misplaced fear.

UPDATE: Yey! He made it home!

Posted in Miscellaneous rubbish | Tagged , , | Comments Off on C-C-C-Cobra Breaker!

In Soviet Russia, pointers dangle you

If words like “C++”, “12 inch rotary debugger”, “dangling pointers” (phhwwoooarr!), “caffeine drip” and “early grey hair” are baffling, confusing or frightening to you, it’s probably best that you skip this post. It’s all technical, boring and generally an opportunity for me to document a mistake that I’ve made in the hope that writing about it will embed it so far in my brain that I will never make it again.

C++ is a cracking computer language with a simple philosophy: it’s all YOUR problem. Allocation of memory? Your problem. Freeing resources? Your problem. Knowing what everything is, where everything is and what state it is in? Your problem. C++ and its cousins, C and Objective C, are relatively straightfoward because they do nothing behind your back. They’re completely faithful. Indeed, you could send student C++ out for the evening wearing a shockingly short skirt to get completely plastered and be 100% sure that she’d behave like the perfect lady. For high-performance, real-time simulation software, games, firmware and an endless bundle of other things it’s a fastastic choice – there’s nothing sneaky going on and you’re in complete control.

The down side, though, is that you have to remember to handle the whole caboodle yourself. Memory management, pointers to objects, etc., all become the programmer’s problem. This can be great, as everything behaves logically and as it should, but it is also an incredible source of bugs and issues for novice and experienced programmers alike. Those that have been doing it for a fair while develop strategies to avoid making common errors and build libraries of their own to help ensure that some of the lowest level crapola can be farmed off to well tried and tested code. Some of my list, for example, you can find here.

And then there’s STL – the Standard Template Library. It’s part of the C++ standard and it adds some truly fantastic higher-level functionality to C++: the kind of functionality that users of almost all other computer languages (except, perhaps, CECIL and assembly language) take for granted. With this handy help, though, comes a cost.

C++ and STL: Cousins in crime!

C++: never does anything behind your back, or indeed, anything at all unless you command it. STL, though, does all sorts of things without you knowing but is better at parties and drinks like a fish.

STL is like C++’s naughty cousin. You can rest assured that if C++ comes home in a police car or ends up in hospital, it’s STL’s fault. She’s the sort of person that is a walking temptation machine: “Here, C++, try these pills, they’ll make you feel great!”.The reason for this is quite simple: STL does do things behind your back in the name of giving you a hand: “Here, I’ll hold the door open for you.” strollstrollstroll “That’ll be a dollar”.

It is, though, a price that generally we’re all happy to pay. Fine, there’s a time and a place and sometimes STL’s box of goodies isn’t appropriate but it’s a fantastic time saver and allows the developer to concentrate on solving the problem at hand rather than reinventing wheels themselves. One of the features that we get in STL are the “Standard Containers”. These are, put simply, variable size arrays. Containers of things that expand and shrink all by themselves or at your command. You can delete items, add items, loop through them and all sorts. One of the most popular is the std::vector. Here’s a simple example:

std::vector vecIntegers;
vecIntegers.push_back(10);
vecIntegers.push_back(11);
vecIntegers.push_back(12);

We now have a list of three integers: the numbers 10, 11 and 12. We can do this:

vecIntegers.erase(vecIntegers.begin());

… and pop! The first one has gone (the experienced STL users are currently frothing and steaming saying “hey, you should be using a deque for that, because vectors are designed for adding and removing at the end only, doofus”. I know, but one likes to keep examples simple without having to introduce the whole of STL, so forgive me.

Here’s another example where we use a vector to store a more complex object: one that has names and ages:

// Declare a structure we'll use to group name and age:
struct NameAndAge
{
	// This, the string type, is also an STL goodie: C++ has no string type as a 
	// basic type:
	std::string	name;		

	// Hahaha! See here for the reason that the C99/C++0x type is used:
	uint16_t		age;	      // Age can't be negative.. or CAN IT?

	// Object constructors to help us:
	NameAndAge() 
	{ return; }
	NameAndAge(const std::string& name_, const uint16_t age_)
	: name(name_), age(age_) 
	{ return; }
	NameAndAge(const NameAndAge& rhs)
	: name(rhs.name), age(rhs.age)
	{ return; }

	// Assignment operator so that we don't cock up the strings as bitwise copies
	// of this object using = will go tits up depending on the std::basic_string 
	// implementation:
	NameAndAge& operator = (const NameAndAge& rhs)
	{ name = rhs.name; age = rhs.age; return (*this); }
};

// Declare a vector type of NameAndAges:
typedef std::vector<NameAndAge> VecNameAndAge;
VecNameAndAge vecNamesAndAges;

// Add some:
vecNamesAndAges.push_back(NameAndAge("Rattlesnake", 10));
vecNamesAndAges.push_back(NameAndAge("The Germs", 2));
vecNamesAndAges.push_back(NameAndAge("Irregular Pigeon", 85));
vecNamesAndAges.push_back(NameAndAge("Giraffe family", 22));

Even if you’re not a programmer, hopefully you can get the gist of that. We end up with a vector containing four objects for four people: Rattlesnake, The Germs, Irregular Pigeon and the Giraffe Gamily. So much wonderful stuff that would normally be your problem has been handled by the vector: it has allocated the memory for you, it has copied the objects across, it has resized itself when it ran out of room… oh, the joy! The joy.

Now, I’m going to start on the road to the bug that took me the best part of a day to track down because I’d made an assumption and not documented that assumption adequately (see item 8 on my list). Here’s another brief snippet that goes in after the above one:

typedef std::vector<NameAndAge*> VecPointersToNameAndAge;
VecPointersToNameAndAge vecPointersToNameAndAges;

// Create another vector of POINTERS TO the items on the first one:
for (VecNameAndAge::iterator itNameAndAge = vecNamesAndAges.begin(); 
	itNameAndage != vecNamesAndAges.end(); ++itNameAndAge)
{
	NameAndAge& thisNameAndAge = *itNameAndAge;
	vecPointersToNameAndAges.push_back(&thisNameAndAge);
}

Danger! Danger! Danger! Wooo-woooo-woooo-woooo! Frankly, if I was doing something like this, alarm bells should have gone off like mad but I had a special case (aren’t they all?) and it was a really, really good way of getting around the problem I had: many objects of different types, all of which inherited a serialisation base class, all of which needed to be serialised… so, after creating all the objects (which were constant, created once at load time and they never changed after that) I simply dumped pointers to them (pointers are the ‘address of’ an object) onto another vector. Then, when it came to data-save-time, I could whizz through the whole lot dead quick and serialise ’em.

And, do you know what, I would have got away with it, too, if it wasn’t for for the unchangable changing.

When you write an application which has a long life-span (many releases over many years) then eventually, regardless of any clairvoyant planning, it will end up doing things that you never imagined. In my case, the bold bit a couple of paragraphs up changed. I had a new feature and it would save me an enormous amount of time if I just inherited an existing object, made a couple of changes to it through overloading and then dumped it onto the array of that object type.

Bingo, it all worked fine.

For a few hours.

Then I had a crash. That’s odd, it was in the serialisation code. I’d not touched the serialisation code in months so what the flying flock of pigeons was going on? Ok, tried a different configuration file (this particular application changes into different applications depending on its configuration – it’s a doppelapplicationgänger) and it worked OK. Right, back to the configuration I was working on, all seems OK… can’t have fixed itself, but I figured I’d wait until the next crash. The data was inconclusive last time (by inconclusive, I mean “I refused to believe it”).

Ah yes, crash number 2. Ok, breakpoints and started stepping through the serialisation code. For some odd reason, one of the objects that was being written was corrupted. So I looked at the list of objects: they were all fine, but the one that was on the serialisation list wasn’t there. How’s that possible? I put the pointer to it on at load-time, I don’t remove anything from the main object list so how could that pointer become invalid?

Honestly, what blog would be complete without this classic Internet picture?

And then I remembered why I had copy constructors: to control how the objects copy themselves when the vector reallocates its memory. This was the Picard face-palm moment: adding the object had exceeded the memory that the vector had allocated so it did its groovy magic behind the scenes: it allocated new memory, copied everything across and continued. This, of course, meant that there was a shiny new set of clones all at new memory locations. My pointers to the objects were pointing to the old objects. The ones that were not there any more. Dangling pointers to random rubbish somewhere – the kind of random rubbish that makes programs go pop. STL had simply moved the furniture around and my code had tried to sit on the sofa at the old position whilst carrying a tray of priceless Fabergé Eggs.

The C++ standard is quite clear on all this (see 23.2.4.2 and more) and much has been said on the subject elsewhere, I just forgot some of the inner workings of a very complex application. I’d not commented the pointer-vector adequately with warnings and I’d not commented the object-vectors that they were to be treated as constants after loads. I could have controlled the reallocations to avoid this by using vector::reserve() to pre-reserve space before allocations would occur, because, as the standard notes:

Reallocation invalidates all the references, pointers, and iterators referring to the elements in the sequence. It is guaranteed that no reallocation takes place during insertions that happen after a call to reserve() until the time when an insertion would make the size of the vector greater than the size specified in the most recent call to reserve().

… but, well, I’d forget I’d done that and one day the application would have more objects than I’d reserved and cryptically crash again. Then I’d lose another couple of days as a result of mixing and matching the way things had been done.

No matter how much care you take, there is a cost of doing things in a hurry. There is an even bigger cost of not documenting why you did things the way you did them. In this case, I solved it properly: took a couple of days out of the main schedule to fix it under the hood, and fix it good so that I could not be baffled by this again. I also wrote this blog post in case I do make this mistake again. Hopefully it’ll pop up on google and I can save myself spending a wonderful sunny spring day with bloodshot eyes staring at the debugger mumbling “that simply can’t be possible. It can’t be possible, it just can’t be possible…”


PS: If you’re a C++ programmer and you don’t have these books, then may I suggest you order them now. They’re incredibly helpful and help you develop good defensive strategies that will ensure you avoid precisely the kind of issue I just had

PPS: I have not actually compiled any of the code in this article, so if it fails, meh, you get what you pay for 🙂

Posted in Software development | Tagged , , , , , , | 1 Comment