nico7et8 nico7et8 - 3 months ago 10
C Question

Change types for error checking in c function arguments?

I've been trying to handle errors in a simple c Library I'm writing. What's the best practice to check for argument errors (or typos) ? Let's say I have a function like this :

int foo (size_t maxSize); // (the int returned is an error type)


Then let's say
foo
goes on to create an array of
maxSize
elements. My problem is this: if by mistake someone uses
foo
with a negative number, then this number is interpreted as a
size_t
and may become very large without warning:

printf ("zu", -10); // 4294967286 on my machine


The program compiles without error or warning,
foo
tries to create a HUGE array, the program stalls at runtime, and there is no immediate way to find that
foo
is the cause (my soul).

How should this be properly handled ? Should
foo
take a
long
which it casts as a
size_t
after checking that it's positive ? (And then return the appropriate error ?). Or should
foo
keep
size_t
and not bother with users who don't follow
foo
signature ?

EDIT ANSWER:

Unanimously, keep the real signature
int foo (size_t maxSize)
otherwise it's misleading (since the max of
size_t
is a valid argument). Let the user handle it, maybe helping him through the docs.

Answer

The question for your library is what is the largest size array that foo should create? Is passing the maximum size of size_t an error? If not then your library can't tell between an erroneous call and a legitimate call that wants a very large array to be created. If you can't tell whether an input is invalid then you should treat it as valid. The users of your library are responsible for catching these errors.

Comments