
Some simple tricks in C/C++ - new_here
https://able.bio/Theocrat/some-simple-tricks-in-c-and-c--755ne2i
======
eqvinox
I'm very much not a fan of indiscriminately typedef'ing structs. To me, a
typedef describes a type as a "fundamental atom". Most structs are ... not
that.

FWIW I also apply the above meaning for typedefs of integer types. It's an
indicator for a "stronger" API boundary, i.e. you shouldn't mess with the
contents.

Also this "Int" typedef in the article triggers a punch reflex for me. Would
give it a hard NAK in any type of review. (Because it would lead to more WTFs
in long-term maintenance of the code.)

------
eqvinox

      sprintf(target, "%s%s", s1, s2);
     
      Now, why would one not just use good old strcat? Well, there are three reasons:
     
      - This is faster. Its about 20% faster than strcat,
        since it accesses the string stored in target with a
        SYSCALL instead of looping over it. I have checked
        using GCC 9.3 on Manjaro with kernel 5.4 (Linux).
    

WTF? sprintf is not a syscall. Also, syscalls make things slower, not faster.

?!?

------
beagle3
The #define new has a , instead of multiplication. It will compile likely
without warning, but cause buffer overflow.

says “use sprintf”, which you shouldn’t do because ... buffer overflow (it’s
possible to avoid but you need to really know what you are doing and set a
maximum length for any conversion, which article authors does not do). For the
same use cases, Proper use of snprintf would avoid overflows.

Other advice seems ok to me.

~~~
sherincall
There are several instances of bad syntax in the article. Easy to make
mistakes if you don't write C daily. I assume they meant to use calloc() here
instead of malloc().

------
traes
> Slap this on the top of your code:

> #define new(dtype,length) (dtype *)malloc(sizeof(dtype),(length))

Kind of a minor point, but isn't the consensus among C programmers that you
shouldn't cast the result of malloc?

~~~
beagle3
On the contrary. you must cast it or get a warning in modern compilers (and an
error if you compile it in C++ mode).

The “don’t cast” consensus is about NULL remaining 0L and not of any pointer
type (as was the case in some standard libraries in the early 90s)

Note also that the comma should be an asterisk.

~~~
fulafel
It's fine in C and you won't get a warning (just try int *p =
malloc(sizeof(int)) with gcc -Wall).

