开发者

c++ Function Argument Editing

i'm making a memory allocation/deallocation function

it's simple

inline void safedealloc ( void *mem )
{
     if ( mem ) { free( mem ); mem = NULL; }
}  

it's working fine .. however after using 开发者_如何学Cit few times with a program

i noticed that when calling it in something like

safedealloc( (char *)name );
safedealloc( (char *)name );

causes error .. name supposed to be null after first call . but it doesn't and the second call with invalid pointer ofc causes error .. why isn't null being assigned to name as it should ?

PS: name is properly allocated using malloc and with valid size and contents


It almost certainly is not working fine, it is pointless, and in C++ the way you allocate memory is with new and delete, not malloc and free. There is no need to check for a NULL pointer - free (NULL ) is well defined in both C and C++. And your assignment of NULL to the function parameter does nothing - it only modifies the parameter, not its value back in the calling program.

And lastly, if you find yourself writing code like this:

char * p = malloc(100);
safefree( p );
safefree( p );

the thing to do is to fix the code so you don't free the pointer twice, not to obfuscate things by sticking a band-aid on bad code.


mem = NULL; doesn't do anything, because mem is a different variable.

Try this instead (notice the & in front of mem, which means a reference to mem):

template<typename T> //I added this due to request, since this doesn't quite work
                     //with pointers other than void*
inline void safedealloc ( T *& mem )
{
     if ( mem ) { free( mem ); mem = NULL; }
}

Whether this is actually a good idea or not is a completely different question.
The answer is No. Why? Because if you made this mistake here, chances are you made the same mistake elsewhere, and the problem just starts all over again, except this time it's higher on the stack and harder to find.


You're trying to change the address inside mem, but this only works on the local argument.

You pass the pointer by value, meaning you can't change the value of the variable the caller has.


You are passing pointer by value, that's the problem. Pass pointer to a pointer, or reference to a pointer, then your assignment will work.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜