Avoid Passing Arguments With Side Effects to C Runtime Library Functions

Avoid Passing Arguments With Side Effects to C Runtime Library Functions

Many of the C Runtime Library functions are in fact macros in disguise. < stdlib.h> routines, memset(), strcpy() and others are often implemented as macros that perform some low-level system call. While Standard C++ strictly forbids this macro in function disguise convention, it is still widely used in C.

You should beware of passing arguments with a side-effect to such pseudo-functions, because the results may be undefined. (A side effect is defined as a “change in the state of the execution environment.” Modifying an object, accessing a volatile object, invoking an I/O function, or calling a function that does any of these operations are all side effects.) To see the potential dangers of passing an argument with a side effect to a macro in disguise, consider the following example:

   char buff[12];  int n = 0;  /* second argument has a side-effect;  bad idea */  memset(buff, ++n, sizeof(buff);  

If memset() happens to be a macro that passes its arguments to another function, the value of n may be incremented twice before it is used.

See also  Comparing different methods of testing your Infrastructure-as-Code

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist