Showing posts with label gotcha. Show all posts
Showing posts with label gotcha. Show all posts

Tuesday, November 25, 2014

Order of Events

inet_ntoa uses static storage for the result it returns. The GNU implementation of inet_ntoa uses the following internally:

static __thread char buffer[18];

This makes the function thread-safe but this safety does not remove the need to worry about use within a single thread. Consider the following snippet of code:

#include <arpa/inet.h>
#include <stdio.h>
int main () {
    struct in_addr a = { .s_addr = 1234567 }, b = { .s_addr = 7654321 };
    return printf ("%s : %s\n", inet_ntoa (a), inet_ntoa (b));
}

Since inet_ntoa is used twice within the argument list the result is dependent on the order of evaluation of the arguments to printf. Regardless of which call gets evaluated first the output will always print the same IP address twice. On my system, the result is:

135.214.18.0 : 135.214.18.0

This is a result of two things: arguments are evaluated before their results are used by printf; and inet_ntoa overwrites static storage on each invocation. Looking at the instructions for this C code makes this clear:

.LC0:                                                                                                                                                                       
        .string "%s : %s\n"
        .text
        .globl  main
        .type   main, @function
main:
        pushl   %ebp
        movl    %esp, %ebp
        pushl   %ebx
        andl    $-16, %esp
        subl    $32, %esp
        movl    $1234567, 24(%esp)
        movl    $7654321, 28(%esp)
        movl    28(%esp), %eax
        movl    %eax, (%esp)
        call    inet_ntoa
        movl    %eax, %ebx        ; pointer stored to static memory
        movl    24(%esp), %eax
        movl    %eax, (%esp)
        call    inet_ntoa
        movl    $.LC0, %edx
        movl    %ebx, 8(%esp)     ; arg2 to printf; pointer from above
        movl    %eax, 4(%esp)     ; arg1 to printf; new pointer, same static memory
        movl    %edx, (%esp)      ; arg0 (format string)
        call    printf
         movl    -4(%ebp), %ebx
        leave
        ret

The correct way to call inet_ntoa consecutively is to save each result to a local variable.

#include <arpa/inet.h>
#include <string.h>
#include <stdio.h>
int main () {
    struct in_addr a = { .s_addr = 1234567 }, b = { .s_addr = 7654321 };
    char ipa[18] = { 0 }, ipb[18] = { 0 };
    strcpy (ipa, inet_ntoa (a));
    strcpy (ipb, inet_ntoa (b));
    return printf ("%s : %s\n", ipa, ipb);
}

Friday, July 19, 2013

Column-Major Confusion

As a programmer coming from a language like C I am used to understanding multidimensional arrays in the following way:
int matrix[3][3] = {
    { 1, 2, 3 },
    { 4, 5, 6 },
    { 7, 8, 9 }
};

Understandably, this is a little bit of a setback when trying to grok how a language such as R handles matrices. The example above is 'row-major' but R uses 'column-major' by default. Note that I'm not describing memory layout here - which coincidentally is the same as my description - I referring to how the matrices are presented to the programmer. To complete the example, here is how I would create the same matrix as above in R:
> matrix(1:9,ncol=3)
     [,1] [,2] [,3]
[1,]    1    4    7
[2,]    2    5    8
[3,]    3    6    9

There is no problem with this per se. In fact, I'd imagine that R programmers that come to something like C may feel similar unease in the paradigm shift. I'm finding that this fact is glazed over in some texts offering an introduction to R. This happens in non-obvious ways. In particular, I found this example today:
> matrix(c(1,0,0,0,1,0,0,0,1),ncol=3)
     [,1] [,2] [,3]
[1,]    1    0    0
[2,]    0    1    0
[3,]    0    0    1

The identity matrix is a particularly bad choice in this regard as it gives no indication of the true layout being used. It is probably good for any tutorial using matrices to cover an obvious simple case first to set the stage before moving directly to something like the identity matrix (or any other symmetric matrix for that matter).

Wednesday, January 25, 2012

Return on Investment

About a year ago, a friend and I were discussing the evolution of learning new tools while working under time constraints. He claimed that, regardless of the pressure, it is almost always better to sacrifice the upfront time in learning a new tool than to stay in your comfort zone to construct the illusion of progress. By illusion he simply meant that early stage progress is shadowed by the long-term effect of having to maintain and update a homegrown solution.

He used the following illustration to convey his point:



The effect is that if you choose to develop your own tools you satisfy the immediate gratification of results but the final solution is more likely to end up as a house of cards.

I had forgotten about this conversation until recently. The program I am currently working on had me in line to provide relevant results in a shortened amount of time. I am working with the llvm compiler infrastructure and it's unique assembly language. Part of what I needed to do is understand, at a high level, the contents of an llvm assembly file. My natural reaction to this was to implement some minimal parser in Ruby to get to a working set of results quickly. Things went well until I wanted to make a decent tool for broader use within the team: I was starting to spend more time on developing the Ruby code than making headway on my tasks. Not only did I dig myself a grave in that respect but since I was quick to satisyfy the initial demand for results I set an expectation that the work was less complicated than it truly is (and will continue to be). I was building a house of cards.

I ended up scrapping the Ruby implementation and I'm now happily coming up to speed on how to manage llvm code with, well, llvm tools. This is not without effect from the leads of the program, of course. Live and learn, I suppose.

Monday, January 16, 2012

Just making sure

I was pouring over some code recently and came across one expression that really made me shake my head:
buff[strlen(buff)] = 0;
I pretty sure the intent was
buff[strlen(buff) - 1] = 0;
Either that, or they really wanted to make sure the string was null-terminated.

Wednesday, September 21, 2011

Go vector or go home

My programming experience progressed mostly along the lines of: C, C++, shell, Java, Java, Ruby, Python, Java, Java. Only recently have I started exploring the likes of Haskell, Erlang and R. Well that evolution bit me a little while back when I tried using an iterative approach in R where a vectorized solution would have been better.

I was dealing with a vector of timestamps that were formatted as 'seconds since the epoch' and what I wanted was to limit that vector to weekend timestamps only.

My naive approach was to construct a simple loop over the values and apply a function to each element. I was only dealing with about 20,000 elements but the time to do this was painfully slow - roughly 20 seconds - so I started investigating an apply-like approach. R provides several ways to do this depending on the input/output requirements: lapply, sapply, and vapply. All three resulted in behavior similar to the simple loop.

The function to test for weekend-ness is as follows:
is.weekend <- function(x) {
   tm <- as.POSIXlt(x,origin="1970/01/01")
   format(tm,"%a") %in% c("Sat","Sun")
}
I don't know the specific details of date/time conversion in R but I was pretty sure that this was not the bottleneck. After a little searching I came upon a different approach. Instead of looping over each element I should have been passing the entire vector around to the functions. I believe that the apply functions take the vector as an argument but do the manual loop internally. However, R supports a more native approach to handling vectors: vectorized operations.

Looping:
use.sapply <- function(data) {
   data[sapply(data$TIME,FUN=is.weekend),]
}

system.time(v <- use.sapply(csv.data))
  user  system elapsed
19.456   6.492  25.951

Vectorized:
use.vector <- function(data) {
   data[is.weekend(data$TIME),]
}

system.time(v <- use.vector(csv.data))
 user  system elapsed
0.032   0.020   0.052

Duly noted.

Tuesday, July 26, 2011

typedef[ine]

The typedef keyword introduces a new type. The #define directive provides a textual substitution mechanism. When does this matter? Consider the following source:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#include "str_type.h"

size_t length (CharPtr str) { return strlen(str); }

void message () {
    CharPtr str = malloc (255);
    if (! str) { return; }
    strcpy (str, "The Message");
    printf("%s\n", str);
    free (str);
}

int main () {

    CharPtr str = "Some Static String";
    CharPtr str1, str2, str3;

    printf ("Length: %d\n", length (str));
    message ();
    printf ("sizeof(str1): %d\n", sizeof (str1));
    printf ("sizeof(str2): %d\n", sizeof (str2));

    return 0;
}

If str_type.h contains

typedef char * CharPtr;

Then the output of running that program is

Length: 18
The Message
sizeof(str1): 8
sizeof(str2): 8

However, if that file contains

#define CharPtr char *

You instead get

Length: 18
The Message
sizeof(str1): 8
sizeof(str2): 1

Notice that since the CharPtr is no longer a type you get

char * str1, str2, str3;

after the processing phase of translation and the asterisk only binds to the first variable leaving the remaining two as plain char variables.

Use #define directives only to provide textual substitution prior to translation; it does not interact with - or compliment - the type system.

Sunday, March 13, 2011

Disappearing Ink

This is something I've been wanting to post about for a while now. There was thread on a forum I used to frequent (under a different handle). You can follow the link for details, but the main concept was that in a transition to a GUI environment the developers needed to intercept printf and fprintf calls and do something GUI-related when the GUI was running and leave the software as-is when the GUI was not running. The approach to handle this was to define their own version of the functions and handle the context there. Something like:

extern "C" int fprintf (FILE *__restrict __stream,
       __const char *__restrict __format, ...)
{
   va_list args;
   int return_status = 0;

   va_start(args,__format);

   if (is_gui && (__stream == stdout || __stream == stderr)) {
       return_status = showMessageInGui(NULL, __format, args);
   }
   else {
       return_status = vfprintf(__stream, __format, args);
   }

   va_end(args);
   return return_status;
}

Which only worked part of the time. Complicating matters was the behavior was different across multiple compiler versions: gcc4.2.4 exhibited the problem while gcc3.4.2 did not.

I did some digging around and found out that the newer version of gcc was actually implementing a level of optimization that undermined the approach of redefining printf. Basically, any argument to printf that did not contain a format string (%) to be filled in resulted in a translation by later versions of gcc to a call to fwrite (or puts). For example:

#include <stdio.h>
int main () {
    printf ("With args %d\n", 10);
    printf ("Without\n");
    return 0;
}

Translates to

.LC0:
    .string "With args %d\n"
.LC1:
    .string "Without"
    .text
    ...
    movl    $.LC0, %edi
    movl    $0, %eax
    call    printf
    movl    $.LC1, %edi
    call    puts
    movl    $0, %eax

Notice the puts call for the second call to printf. So regardless of what definition was provided for printf the code would never be executed. Try it with the following:

#include <stdio.h>

int printf (const char * fmt, ...) { return 1/0; }

int main () {
    printf ("w00t\n");
    return 0;
}

You'll see that a warning is presented (for division by zero) but the code runs without issue.

There were several solutions presented in the thread but the OP eventually chose to use gcc flags to prevent this behavior. Using -fno-builtin-fprintf and -fno-builtin-printf allowed compilation without the translation and the redefinition of printf worked as expected.

Saturday, January 22, 2011

C++ namespace

 
 
using namespace std;

It appears in almost every tutorial for beginners and the vast majority of books dedicated to C++. I suppose it saves more time than the alternative of teaching the proper mechanics to newcomers. For the most part, I suspect that you may never have a problem using the standard namespace in it's entirety. I think it's unfortunate, however, that this approach hides both the intent of namespaces and the pitfalls associated with not understanding their mechanics.

A namespace is a clarification tool: it announces the intended scope of the token it proceeds. If you have two tokens with the same name, placing them in separate namespaces prevents compilation errors due to name clashes. There are other functions of namespaces, such as clarity of code, but these are considered secondary if at all.

I've heard - and argued against - people who claim that using an entire namespace is perfectly fine and any claims to the contrary are bunk. To be clear; understanding namespaces is not as important as understanding pointers, references and proper use of classes. But, there are things to watch out for especially as a beginner. Most notably: masking and ambiguity.

Masking
The problem here is that including an entire namespace can mask errors in your own code. This example is something that is very common in those starting out in C++, particularly if they are coming from a scripted language background.

#include <iostream>
#include <algorithm>

using namespace std;

int main () {
    int x = 5, y = 3;
    cout << "Before swap: " << x << " " << y << endl;
    swap (x, y);
    cout << "After  swap: " << x << " " << y << endl;
    return 0;
}

void swap (int x, int y) {
    int tmp = x;
    x = y;
    y = tmp;
}

The intention is obviously to swap the values of two numbers. As it is written however, this swap will only modify the local variables leaving the original two unchanged. The problem lies in the fact that there is a std::swap defined that does the appropriate thing and we get:

Before swap: 5 3
After  swap: 3 5

Which is correct but masks two things that a beginner now won't notice: 1) the local swap is not recognized by the compiler before the use in main (no prototype) and 2) the std::swap version is being invoked and masking incorrect behavior.

If, instead of the entire namespace, we only used specifically the elements local to our scope we would resolve these issues. Changing 

using namespace std;
to 
using std::cout;
using std::endl;

would result in a compilation error similar to:

mask.cc: In function ‘int main()’:
mask.cc:10: error: ‘swap’ was not declared in this scope

Ambiguity
This is a problem of name clashing: two equally qualified matches to a function are present and the compiler can not discern which is to be used. There is a similar problem when two names clash and scope can be used in determining which function gets used. This is an even more subtle bug since there are no complaints from the compiler your code just uses the function with the innermost scope regardless of your intentions.

Consider:

namespace foo { void fun() { } }
namespace bar { void fun() { } }

using namespace foo;
using namespace bar;

int main () {
    fun();
    return 0;
}

Trying to compile that results in

ambig.cc: In function ‘int main()’:
ambig.cc:8: error: call of overloaded ‘fun()’ is ambiguous
ambig.cc:2: note: candidates are: void bar::fun()
ambig.cc:1: note:                 void foo::fun()

That is a painfully obvious example but working with much larger projects where multiple teams are committing code this becomes a real problem. Again, using only the relevant portions of a namespace or being specific when calling the function (bar::fun(), for example) solves this problem.



Another benefit of understanding how to use namespaces is cleaner code in some settings. Consider some of the code you may have seen for multi-platform projects:

void fun () {
#ifdef PLATFORM1
std::cout << "platform1::fun()" << std::endl;
#else
std::cout << "platform2::fun()" << std::endl;
#endif
}

with the logic of the platform sprinkled within the function bodies themselves. This is hard to read and even harder to maintain. With namespaces this can be cleaned up to separate each function body (one for each platform) into it's own namespace.

#include <iostream>

namespace platform1 {
    void fun () {
        std::cout << "platform1::fun()" << std::endl;
    }
}

namespace platform2 {
    void fun () {
        std::cout << "platform2::fun()" << std::endl;}
}

Now, the only place that needs platform logic is when we decide to use the namespace.

#include "platform.hh"

#ifdef PLATFORM1
namespace platform = platform1;
#else
namespace platform = platform2;
#endif

int main () {
    platform::fun ();
    return 0;
}

I can't remember ever seeing this approach suggested instead of the less robust macro everywhere code.



Again, with all errors you can run across in a C++ program the ones listed above are some of the easier to pinpoint. Beginners will have the most difficulty as they are not only struggling with a new language and syntax but with subtle errors that are masking behavior they don't even realize is incorrect. I don't think that teaching the proper use of namespace adds that much complexity to learning C++; it really is unfortunate that the topic is not done justice in most reference material.