Handle the char array returned by the C function

I use the tinyXML library, which parses XML files. Many of its methods return const char *.

After reading this question: how to return a char array from a function in C

Now I suppose that every time the method returns char *, it is responsible for the call (mine) to explicitly release it, because it is probably dynamically allocated on the heap. Right wrong? What can I guess?

(If I ever wrote a library, I would rather return std :: string instead of char * arrays, because they are much easier for the user.)

+8
c ++ c arrays pointers memory
source share
2 answers

You cannot accept anything and must check the documentation for the method you are calling to see if you should free the pointer or not. Sometimes a function returning const char * can return a statically allocated string:

 const char *getName(){ return "SPQR3"; } 

Or it could be a pointer, which is another responsibility for exemption. For example, the strcpy return value matches the pointer that you pass to it as input.

+7
source share

Read the library documentation. Both uses (a pointer to an internal buffer or a pointer to a dynamically allocated buffer) are common and do not differ from the function prototype alone.

+5
source share

All Articles