OpenSource For You

Non-reentrant functions

-

A function is 'reentrant' if it can be safely called again (i.e., it can safely 'reenter' the function) even if it is already part of a call. For example, assume that a function is interrupte­d by a signal. Now, if the function is entered again from some oWhHr FonWrol flow, LW shoulG bH sDIH Wo HxHFuWH WhDW IunFWLon; now, after this reentered execution completes, the original invocation should be able to complete execution safely.

A function is 'non-reentrant' if it cannot be safely called again if it is already part of a call. Many of the library functions in the original C library are non-reentrant. In general, stateful functions (which we discussed just now) DrH non-rHHnWrDnW. So, WhH sWDnGDrGs hDYH GHfinHG HTuLYDlHnW C library functions that are reentrant. For example, strtok_r is a thread-safe alternativ­e to strtok. Note the ‘_r’ suIfix—LW stands for ‘reentrant’. A few examples of reentrant variants of C IunFWLons DrH: rand_r, asctime_r, ctime_r, and localtime_r.

Now, depending on the argument values, the behaviour of realloc changes. If size < original block, it shrinks the block; if size > original block, it expands the block. Now, if ptr is NULL, LW Ls HTuLYDlHnW Wo FDllLnJ malloc(size); if size Ls HTuDl Wo zHro and ptr is not NULL, LW Ls HTuLYDlHnW Wo FDllLnJ free(ptr). If the ptr JoW PoYHG, WhHn LW Ls HTuLYDlHnW Wo free(ptr). Yes, from this descriptio­n it is clear that the designer of realloc has made it smart — based on the argument values, the behaviour of the function changes. However, preferable to ‘smart programmin­g’ is ‘simple and straightfo­rward programmin­g’ in API design, and an important aspect of keeping functions simple is to let each do one thing and do it well.

I have listed some of the mistakes or problems in the C library. The list is not exhaustive but is just meant to give you an idea of the kind of API design problems in the C library. Good designers not only learn from their own mistakes, but also from others’ mistakes and from the past. I hope this list has motivated you to improve and become a better designer.

 ??  ??

Newspapers in English

Newspapers from India