-1

Say we have some function and we want to validate the arguments. For instance for not being NULL:

void* myFunction(char* str1, char* str2){
    if(str1==NULL || str2==NULL) return NULL;
    ...
}

My question is what it is called a good low-level (APIs) validation like it is made by standard C libraries.

Thanks.

Sanich
  • 1,739
  • 6
  • 25
  • 43
  • 1
    The C standard library is not guaranteed to validate arguments. `strcpy(NULL, "abc");` will probably crash. This is fine. – Dietrich Epp Dec 06 '12 at 01:34

2 Answers2

1

C is a what you ask is what you get language with lots of rope to hang yourself and very little safety nets. Take for example this implementation of strcpy from Apple, but they all look very much alike:

char *strcpy(char *s1, const char *s2)
{
    char *s = s1;
    while ((*s++ = *s2++) != 0)
    ;
    return (s1);
}

As C doesn't know the concept of exceptions, all error signalling has to be done via the return value of the function and sometimes via the global variable errno, which of course somewhat limits the expressivity of errors.

So, if you want to keep in line with what the standard library does, very little safety needs to be provided.

fvu
  • 32,488
  • 6
  • 61
  • 79
  • As i understand, in your example the validation of NULLs is made as part of the implementation of the functionality itself. – Sanich Dec 06 '12 at 01:42
  • @Sanich indeed, the code calling the function is itself responsible for the correctness of the parameters it sends. The library function assumes the values it receives are usable. – fvu Dec 06 '12 at 10:01
0

The key thing is to "do what you say" and "say what you do". "What you say" needs clearly described. The description should be in the documentation, but can also be in comments or the function name or parameter names.

Having stated the requirement, make really sure that you then meet that requirement. If you define error cases to trap, make sure that the caller can determine this using errno or otherwise.

Keith
  • 6,756
  • 19
  • 23