Recursive Complexity

Thoughts and musings of a programmer and wanna be entrepreneur

What’s wrong with this piece of code ?

with 6 comments

struct foo {
    int a, b;

void kstrtol(long *x)
    *x = -1;

int main(void)
    struct foo foo;
    foo.b = 42;
    kstrtol((long *)&foo.a);
    return 0;


Written by Vivek S

July 23, 2013 at 4:02 pm

Posted in Tech

Tagged with , , , ,

6 Responses

Subscribe to comments with RSS.

  1. Its the long casting of foo.a. It eats into foo.b since they are contiguously allocated as int. Overwrites foo.b which has 42 with -1 too. Added this line to confirm –

    printf(“%d – %d”, foo.a, foo.b);
    kstrtol((long *)&foo.a);
    printf(“%d – %d”,foo.a, foo.b);

    Prints –

    1380330456 – 42-1 – -1


    July 24, 2013 at 5:39 am

    • What about on a 32 bit system ?

      Vivek S

      July 24, 2013 at 6:21 am

      • What about that? Anyways who cares about 32 bit. Its vintage.

        Vikram Rao

        July 24, 2013 at 6:26 am

      • As a developer don’t assume things. Make sure you cover all scenarios. At least that’s what I have come to learn while developing drivers and OS components. 32-bit OSes are still there and will be for sometime. The underlying concept I wanted to highlight was that while writing code, keep in mind the different architectures your code might run on. Test on those different architectures. I came across this on the Linux kernel mailing list where a patch got rejected because the developer didn’t think on the above lines.

        Vivek S

        July 24, 2013 at 6:32 am

  2. struct foo foo ; ? I think you are mistaken here only…

    also defining two variables in one line in a struct(a, b), not too sure about this either…

    mayank gupta

    July 23, 2013 at 6:05 pm

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

TED Blog

The TED Blog shares interesting news about TED, TED Talks video, the TED Prize and more.

%d bloggers like this: