Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Would strlen() be possible with Rule 17.4?
#2
The purpose of Rule 17.4 is to limit the general use of pointers in order to make code easier to review and analyse. If an object is declared with a pointer type, the assumption is that it is being used only to access a single object or array element. If access to more than one element is required then the object should be declared with an array type instead.

When a parameter is declared with an array type, it is treated as if it were a pointer to the first element of the array instead. However, for the purposes of Rule 17.4, parameters declared with an array type are treated as arrays. It is therefore only possible to perform arithmetic and array indexing on an object only when it is declared as an array.

An important consideration about Rule 17.4 is that it looks only at the form of the declaration of a pointer or array object and does not consider the type of the underlying object to which the pointer or array points.

Therefore it is possible to pass either a pointer or an array as an argument to a function that is expecting an array parameter. In this way, it would be possible to write strlen as:

Code:
size_t strlen (const char s[ ])
{
  size_t len = 0;

  while (s[len] != '\0') {
    ++len;
  }

  return (len);
}
It would be possible to pass any "array of char" or "pointer to char" to this version of strlen() and comply with Rule 17.4.

Of course, the standard declares strlen as:

Code:
size_t strlen (const char *s);
so the implementation using an array is not permitted and it is not possible to write the standard strlen without deviating Rule 17.4. While this is unfortunate, it is felt that the benefits of applying Rule 17.4 to application code outweigh the inconvenience of having to use deviations for a standard library.
Posted by and on behalf of the MISRA C Working Group
Reply


Messages In This Thread

Forum Jump:


Users browsing this thread: 1 Guest(s)