safe function calls

Started by
9 comments, last by Antheus 16 years, 3 months ago
i would like a some kind of function that would take a function pointer and several arguments then check if all (or just the first?) the arguments != NULL and then call the pointed function with those parameters... it would be nice to have it as general as possible... is that possible? it would be something like this SAFE_FUNCTION(SetValue, Pointer, Value); void SetValue(int* Pointer, Value) { *Pointer = Value; }
Advertisement
If this is C++, use a reference. A reference cannot be NULL.
If you are programming in C++, the solution is simple: don't use pointers. Use references instead: references cannot be null.

If you are restricted to using C, you could use assertions or Linus' trick:
void SetValue(int *dest, int src) {  assert(dest);  *dest = src;}void SetValue(int *dest, int src) {  if (!dest) return;  *dest = src;}

Yes. Use references.

Other way is:
template < class T >class SafePtr{  SafePtr(T * p)  {    if (p == NULL) throw // some exception  }  T * operator->() { return ptr; }  T & operator*() { return *ptr; }private:  T * ptr;};


Quote:
If this is C++, use a reference. A reference cannot be NULL.


void Foo(int& a){	std::cout<<"This cannot be null(or can it?):"<<a<<std::endl;}int _tmain(int argc, _TCHAR* argv[]){	int* a;	a=NULL;	Foo(*a);	return 0;}


Morale: C++ is fucked up.
Quote:Original post by mikeman
Quote:
If this is C++, use a reference. A reference cannot be NULL.


*** Source Snippet Removed ***

Morale: C++ is fucked up.


Well, the C++ language says that code has undefined behaviour. References cannot be NULL. That code is meaningless, it is certainly not standard C++.
        int* a;	a=NULL;	Foo(*a);  // <-- here you are dereferencing NULL pointer, thus causing undefined                  // behaviour.  This means *anything* can happen.



Quote:Original post by mikeman
Morale: C++ is fucked up.


I'm pretty sure that a = NULL; *a; is also incorrect in C. The fact that C++ considers lvalues to be manipulable (in the form of reference variables) doesn't change anything about lvalues not being NULL in either C or C++.
In theory you're all right of course, but in the real world bugs like that can(and most probably will) appear, and there's little you can do to defend against them. And protection against bugs is the primary reason we're using references anyway. My point was to show that references are far from bullet-proof. You certainly can't check a reference for nullity(well you can, but you shouldn't).
Quote:Original post by mikeman
In theory you're all right of course, but in the real world bugs like that can(and most probably will) appear, and there's little you can do to defend against them.


Use moar references! Seriously, the less naked pointers you have in your code, the fewer places you risk dereferencing a NULL one.

This topic is closed to new replies.

Advertisement