-1

I am facing compilation error in the below code. I am writing a function to free memory in C++

template<class T> inline void kill(T& v)
{
   free(v);
   v=0;
}

I am calling this function for freeing Class object and sometime to free a string and getting below error.

Error 1 'void free(void *)' : cannot convert argument 1 from 'const char *' to 'void *'

Error 2 'void free(void *)' : cannot convert argument 1 from 'Cstring ' to 'void *'

If I change the code like below then no error.

template<class T> inline void kill(T& v)
{
   free((void*)v);
   v=0;
}

Any other better solution for this?

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
  • 1
    Why are you using `free` in C++? – user657267 Nov 07 '14 at 06:59
  • I have used 'C' code also. I want to free C objects. – techQuery Nov 07 '14 at 07:00
  • If the objects to be freed are allocated by `malloc` then the second example should be good. – Logicrat Nov 07 '14 at 07:03
  • 1
    @techQuery Then why are you using C in C++? – user657267 Nov 07 '14 at 07:08
  • `CString` is definitely not a `C` object (unless you have objects that are exactly the same name as the ones used in Windows by C++). What exactly are you trying to free - can you make an example. And yes, you will need to cast to `void*` just like your allocation does `T* ptr = (T *)malloc(sizeof(T));` when allocating it. – Mats Petersson Nov 07 '14 at 08:33

2 Answers2

0

It will be good if you have mentioned the compiler you are using.

In Visual studio 2008 I tried to compile your code (first example)and it is working.

The answer is, if compiler is not allowing, what you can do.

You have to go with the second example code only.

But generally compilers should allow that.

Neo
  • 21
  • 4
0

free should be used exclusively on pointer which you got from malloc. A T& is a reference. Unless that's a reference to a pointer, your code makes no sense. References to pointers are rare enough, but C++ references to pointers returned by C's malloc are even rarer. Your code is highly suspect and very error-prone.

MSalters
  • 173,980
  • 10
  • 155
  • 350