← Back to context

Comment by dmitrygr

12 hours ago

Lucky for us C programmers. Each distro provides its own trusted libc, and my code has no other dependencies. :)

Do you rewrite fundamental data structures over and over, like maps, of just not use them?

  • Often yes, specialized to the specific thing I am doing. Eg: for a JIT translator one often needs a combo hash-map + LRU, where each node is a member of both structures.

But how do you left pad a string?

  •     char * 
        left_pad (const char * string, unsigned int pad)
        {
            char tmp[strlen (string)+pad+1];
            memset (tmp, ' ', pad);
            strcpy (tmp+pad, string);
            return strdup (tmp);
        } 
    

    Doesn't sound too hard in my opinion. This only works for strings, that fit on the stack, so if you want to make it robust, you should check for the string size. It (like everything in C) can of course fail. Also it is a quite naive implementation, since it calculates the string size three times.

    • Not a C expert but you’re using a dynamic array right on the stack, and then returning the duplicate of that. Shouldn’t that be Malloc’ed instead?? Is it safe to return the duplicate of a stack allocated array, wouldn’t the copy be heap allocated anyway? Not to mention it blows the stack and you get segmentation fault?

      2 replies →