• About Me
  • Blog
  • Home

Eric Hokanson

~ E's little space in cyberspace

Eric Hokanson

Category Archives: Programming

An Interesting “Gotcha” in C

19 Tuesday Aug 2014

Posted by Eric Hokanson in Algorithms, C Programming, Computer Programming, Computer Science, Programming, Software Development

≈ 4 Comments

Tags

Arrays, Arrays and pointers, Arrays passed into functions, C gotchas, C programming, Calculating the size of an array, Pointers, sizeof()

Consider the following function:

Screen Shot 2014-08-19 at 2.57.34 PM

The function takes an array and uses recursion to check if that array is in sorted order.  For example, an array containing: {1, 2, 3, 4} is in sorted (ascending) order.  So is the array: {2, 2}, or an array with only one element, such as: {0}.  But the array: {44, 3, 25, 88} is not.  A pretty simple, elegant, little function, right?  But, there is a potential danger.  Can you spot the problem?

I have been doing a lot of C programming for a project this summer (C is a customer requirement) and I have run across lots of libraries, and functions similar to the one above.  Namely, some function passing in an array, then iterating over the values of that array to print the contents or perform some computation over the elements.  In C, if you pass in an array as a function argument, you must also pass in the number of elements or size of the array.  Why?  In C, array parameters are treated as pointers and with out n, the size or number of elements contained in the array, we have no way of calculating the size of an array given its pointer.

A common mistake made by inexperienced C developers is to do:Screen Shot 2014-08-19 at 3.27.11 PM

That only works if you are dealing with arrays that are NOT received as parameters.  An array passed in as a parameter is treated as a pointer, the sizeof function will return the pointer’s size instead of the array’s.  Not what we want.

The potential danger of the function above, and consequently many functions that take in arrays (at least in C that I have noticed), is the assumption that the caller will do the right thing.   But accidents happen.  What happens when a caller passes in an array that is smaller than the size (e.g. isArrayInSortedOrder(A[2], 5) )?  We wind up exceeding the bounds of the array and crash the program and that belongs in the “bad things” category.

So how does one perform some form of sanity check when passing in an array and a size?  Don’t use C, use C++ or Java where array objects natively “know” their size?  Would if I could but customer constraint, remember?  Must be in C.  Convince the customer not to use C?  Fine, but what if you are developing on an embedded system?

Ok so we are stuck with C, a non-reflective language where objects don’t automatically know about themselves like their sizes.  One solution: we could write a macro to wrap the call, calculate the size of the native array before passing it in as a parameter, then adding our calculated size as a parameter.  That way, the caller would only need to pass in the array and not have to worry about getting the size right.  Something like the following:

Screen Shot 2014-08-19 at 3.55.00 PM

Notice the #define on line 15.  We name our wrapper function with one parameter in terms of our original but slightly modified array checking function.   The size of the native array is calculated first and then passed in as the second parameter, the int n.  One other note:  obviously a developer can see the original function declaration and there is nothing preventing the developer from calling that function directly bypassing my wrapped solution.  We would need to do a better job of “hiding” the original.  But for demonstration purposes, this will suffice.

In our modified implementation, we can add some sanity checks to deal with empty arrays or if n becomes a negative number for some weird reason:

Screen Shot 2014-08-19 at 4.02.30 PM

By wrapping our function in a macro, we simplify the implementation a bit for the user. They only have to pass in an array and the wrapper will calculate the size on behalf of the caller thus potentially minimizing our risk of passing in an incorrect array size.

To test our solution, we can do:

Screen Shot 2014-08-19 at 4.12.21 PM

Since array3 is empty, the above should print that the array is not sorted.  Change the array parameters and you should find that arrays 1, 2, and 4 should print that the arrays are sorted, while array 5 is not sorted.

An interesting little conundrum in C that I never really put much thought into until I started doing more intensive C programming projects.  I would be interested in hearing your thoughts on handling situations like the above, or others gotchas.  Feel free to drop me a line.  Until next time, we’ll C you later.

Quote

Debugging

08 Thursday May 2014

Posted by Eric Hokanson in Programming, Reverse Engineering, Software Development

≈ Leave a comment

Tags

Brian Kernighan, Debugging, programming, Reverse Engineering

Debugging is twice as hard as writing the code in the first place.  Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.

Brian Kernighan

To Learn to Code or Not

29 Sunday Dec 2013

Posted by Eric Hokanson in Programming

≈ Leave a comment

Tags

Code, Computer science, Education, Learning, programming

There has been a lot of discussion lately on the importance of learning to code.  And I have added my two-cents.  Maybe three.

Here is an interesting opposing viewpoint: You don’t need to learn to code and other truths about future careers.  It is the only opposing view I have seen so far.  The author argues that coding is not for everybody.  If you hate coding, then forcing yourself to learn just to stay competitive in the job market, would be a miserable way to go.  And you are not likely to be successful in a job you hate.

Secondly, learning to program just to launch a career change is likely to end in frustration.  Going from no programming experience to a programming job, while not unheard of, is rare.  Many tech companies today have a grueling application process requiring you to demonstrate proficiency and that takes years to master.  Up to 10 years in some studies I have seen.

It is always good to hear the other side of an argument.  Learning to program may not be great career advice.  However, what is the harm in learning for fun?  For your own personal benefit?  Programming is not some big mysterious skill that can only be done by a few hoodie clad brainy types.  Anyone can learn to code and some languages are remarkably easy pick up.  While it may take a decade for mastery, the fundamentals can be picked up in as little as a few weeks.  And you can create some amazing things almost right away.  There is no reason not to try your hand at programming.  See if you like it.  Creating your own web-sites or apps can be fun even if no one ever sees your creations.

To actually learn how to think. I think everyone in this country should learn to program a computer. Everyone should learn a computer language because it teaches you how to think. I think of computer science as a liberal art.

Steve Jobs from the lost interviews

Speaking from personal experience, programming has sharpened my problem solving skills and it will sharpen yours too.  Becoming a better problem solver is a skill that will benefit everyone.  No matter the job market situation: if you can solve problems then you will always have a job.  The market is already flooded with people that cause problems, but we could always use a few more problem solvers.

Related articles
  • Don’t Waste Your Break! Learn Something!! (drkblog.wordpress.com)
  • Learning Code – Keep on Trekking (codemoms.wordpress.com)

Computer Science Education Week December 9 – 15

07 Saturday Dec 2013

Posted by Eric Hokanson in Computer Science, Learning, Programming

≈ 1 Comment

Tags

Computer science, Newton's method, programming, Python, Square root

Teaching students programming and computer science one hour of code at a time.  Here is the official site where you can learn how to become involved.   I thought I would take an opportunity here to make my contribution.  In this lesson, I will use as my guide, a great introductory to Computer Science (CS) text, often referred to as the “purple” book, or the “wizard” book.

What is Computer Science?

Computer science is really a misnomer.  It is not a science.  We don’t study a system, observe phenomena, and run experiments to validate a hypothesis.  Computer science is not a study of computers anymore than biology is the study of microscopes.  A computer is simply a tool.  And computational devices come in many different forms.  There are the silicon-based binary gadgets that you use everyday, like laptops, tablets, and smart phones.  But they are poor imitations of the most powerful computing device ever created: the human being.  We are a bio-mechanical machine, performing our computations in base 10.  And of course, we are capable of much, much more.

Declarative and Imperative Knowledge

Computer science is not a science; it is more of an art — an engineering practice.  Computer science is really about knowledge.  The knowledge of how to do something: solve a problem, perform a task in a methodical, mechanical process.  This process is called imperative knowledge.  It is the knowledge of how to do something.  Declarative knowledge, on the other hand, deals with the facts.  Let me illustrate with an example found in the purple book.

Example: Square Roots by Newton’s Method

An example of declarative knowledge:

The above is a fact about square roots.  You can find it in any basic math text.  In words: the square root of any number x, is a number y, where y is a positive number, and if I multiply y by itself.  I get x.  For example: let x be 4, then y must be 2 because 2 times 2 equals 4.  You can reason the same for 16, or even 625.  Larger numbers are harder.  You may have to make some educated guesses before you stumble upon the correct answer.
Well, that is all fine and dandy.  But what if you were given: \sqrt{2} ?  How can we use the above declarative knowledge to figure that out?  And that is the problem of declarative knowledge.  It doesn’t tell you how to calculate the square root of 2 — or how to find the square root of any number.  The declarative statement can only tell you how to recognize a square root if you saw one.

Newton’s Method

To solve the square root of any number, we will use a very old algorithm called Newton’s method.  Ironically, the method starts with a wild-ass guess (a WAG, we call it in the scientific and engineering community).  Then we refine our guess with successive approximations until we get to an answer that is good enough for government work.  Let’s construct our algorithm based on Newton’s method:

To find the approximation of the square root of x:

  1. Make a guess G
  2. Improve guess G by averaging G and x/G
  3. Keep improving until the guess is good enough.

Simple, right?  Don’t take my word for it.  Try it out.

table

Compare the 1.4142 with your calculator’s square root button.  You should see the 1.4142 plus a bunch of other numbers.  We solved out to four decimal places (to the 10-thousandths place), and that is good enough for us.

Now let us write this out as a recipe of instructions:

Square Root X:

  1. Make a guess G
  2. Is it good enough?:  absolute_value(G*G – X) < 0.0001 then G is the answer and we can stop; otherwise go to next step
  3. Improve guess G: G = (G + X/G)/2
  4. Repeat step 2.

So let’s step through our recipe.  First make a Scientific Wild-ass Guess.

Next we test our guess by, first squaring our guess and subtracting that guess with X.  We take the absolute value because your guess may be less than the square.  For example, in the square root of 2, our first guess was 1.  1 – 2 = -1 and we don’t want a negative number because we are measuring the distance between our guess and the perfect square X.  And since negative distances don’t make sense, we take the absolute value, which means we first remove the negative sign, and then see if the answer is within some threshold of tolerance.  In this case, less than one-ten-thousandths.  Or put another way, we will keep refining our guesses until we calculate the square root to four decimal places.  If our guess is less than our threshold, then we stop and G is our answer.  If not, we go to step three to improve our guess and repeat the process.

Try our recipe above out with a piece of paper and a calculator and see if you get the same results as in the table above, if you let X = 2.

If you made it this far, my dear reader, I want to congratulate you.  Together we wrote a computer program.  Our program is not in a traditional computer language like C, or C++, or even Python.  But it is in the language of English and math.  Any reasonably intelligent human computer, with some knowledge of middle school, or high school math should be able to follow our recipe (algorithm) and effectively become the square root button on a calculator.

I hope the above example gives you an idea of what programming and computer science is about.  Now, if you really want to learn a programming language, first pick a language and a site you can learn from.  I recommend code academy and the language of Python.  Python is very easy to learn.  Once you get the basics and the syntax down, see if you can take our little recipe above and translate it into your new language, and get a computer to do all this hard math stuff for us.

Related articles
  • Bubble Name Animation (devguy.co)

An Idea on How to Learn Programming and Software Development?

27 Wednesday Nov 2013

Posted by Eric Hokanson in Programming, Software Development

≈ 2 Comments

Tags

How to Learn How to Program, programming, Software Development

How to learn — or not learn software development

Been reading a lot about the healthcare.gov software development headaches lately.  I am using it as a personal case study of how/when/why software development goes wrong, and how I might be able avoid these issues in any of my projects at the labs.  I have been using the Mythical Man-Month (MMM) as my guide and it is very enlightening how one can learn by observing the examples or misfortunes of others.

What would I do different?

I would seek out the expertise of anyone who has had the experience of rolling out a massively wide scale web service.  Hmmmm… who could that be?  Amazon.com immediately comes to mind.  I am very surprised that the administration didn’t seek them out.  I am not privy to the bidding process so maybe they did; maybe they didn’t.  I get the sense (and this is just my opinion) the administration believes that if you throw a bunch of tech-savvy people at a problem, magical and amazing things will happen.  Obviously that is not always the case and it violates of one of the tenets of MMM.  Another idea: tour several silicon valley companies; how do they utilize the power of the tech-savvy to create amazing things?

An Idea on How to Learn How to Program

Seeking the guidance of an experienced expert, such as Amazon is also a great way to improve your programming skills.  I had the opportunity to meet a few developers at the Amazon booth at a security conference last August.  They had these programming puzzles similar to below (can you spot the issues?):

wchar_t *fillString(wchar_t content, unsigned int repeat)
{
    wchar_t *buffer;
    size_t size;
    if (repeat > 0x7fffffffe)
        return 0;
    size = ( repeat + 1 ) * sizeof content;
    buffer = (wchar_t *) malloc ( size );
    if ( buffer == 0 )
        return 0;
    wmemset(buffer, content, repeat);
    buffer[ repeat ] = 0;
    return buffer;
}

They had many of these and I had fun solving them; learned some new programming techniques in the process.  I thought: wouldn’t this be a great way to learn how to program?  What if we compiled a puzzle book of code with various topics and challenges?  One chapter could be on proper syntax and constructs to help with spotting common errors and to teach debugging strategies.  Another chapter could be on pointers where you play the role of the compiler/computer and “run” the program to see if you understand pointer arithmetic.  A chapter on simple data structures where you draw out the logical implementation of a linked-list or a hash table.  And of course a chapter on security with snippets like those above.  And if we could format the book in such a way that at the start, you are ignorant of the language, but by the end, you could start using your new skills to make things.

I have several friends who play chess and they use puzzle books to improve their game play.  They claim they learn how to spot patterns for end-game scenarios and how to mate in 3 or 4 moves.  Perhaps we could do something similar  but with code.  Perhaps I should consult Amazon.com and see if any such books already exist.

Related articles
  • The Healthcare.gov Debacle and Why We Should Open-Source Everything (businessweek.com)
  • My experience in Software Development without being a Developer – The Beginners Guide (msayem.wordpress.com)
  • It’s an agile world – the sooner you get used to it, the better (venturebeat.com)

Subscribe

  • Entries (RSS)
  • Comments (RSS)

Archives

  • May 2016
  • May 2015
  • April 2015
  • March 2015
  • September 2014
  • August 2014
  • June 2014
  • May 2014
  • April 2014
  • March 2014
  • February 2014
  • January 2014
  • December 2013
  • November 2013

Categories

  • Alan Turing
  • Algorithms
  • Apollo 17
  • C Programming
  • Christmas
  • Computer Programming
  • Computer Science
  • Computer Security
  • Current Events
  • Cyber Security Research
  • Education
  • Freedom of choice
  • Freewill
  • Hacking
  • Holidaze
  • Learning
  • Malware RE
  • Math
  • NASA
  • Pen-testing
  • Philosophy
  • Pi Day
  • procrastination
  • Programming
  • Python
  • Quine programs
  • Quotes
  • Random Stuff
  • Research
  • Reverse Engineering
  • Shopping
  • Smithsonian National Air and Space Museum
  • Software Development
  • Star Wars
  • Success
  • Uncategorized

Meta

  • Register
  • Log in

Blog at WordPress.com.

  • Follow Following
    • Eric Hokanson
    • Join 44 other followers
    • Already have a WordPress.com account? Log in now.
    • Eric Hokanson
    • Customize
    • Follow Following
    • Sign up
    • Log in
    • Report this content
    • View site in Reader
    • Manage subscriptions
    • Collapse this bar
 

Loading Comments...