'In a library, should I check if pointers are valid?
I've wondered this for a while and the necessity of checking whether pointers are valid or not in my own library is even necessary. Should I just expect the user to pass in the correct pointers because it's their job if they're using the library?
For example if I have a library which allocates and returns a structure
struct some_context{
uintptr_t somedata;
};
struct some_context* createsomecontext(void){
return malloc(sizeof(struct some_context));
}
But then I want to operate on that structture
void dosomethingwithsomecontext(struct some_context* ctx){
//which is more valid here?
assert(ctx);
//or
if(!ctx)
return;
//do something with ctx
}
Does it make more sense to call assert, or check if the structure is valid and return if it isn't? Should I not even bother with checking the pointer and just assume the user is going to do the right thing? And same thing with cleanup
void destroysomecontext(struct some_context* ctx){
//Which is more valid?
assert(ctx);
//or
if(!ctx)
return;
//do cleanup
}
What's more appropriate? assert, if ,or neither? Similarly if I'm even writing a function to operate on a string?
void dosomestringoperation(char* str){
assert(str);
//or
if(!str)
return;
}
Should libraries ever do these checks ? At least in user mode, I can understand in the kernel since every device has access to the global memory and can cause a crash by not checking but does that imply even usermode applications should check for security/sanity reasons?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
