8

I am using a library called tinyXML, which parses XML files. Many of its methods return a const char*.

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

I now believe that every time a method returns a char* it is the caller's (my) responsibility to explicitly free it, because it is probably allocated dynamically on the heap. Am I right / wrong? What can I assume?

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

1
  • grinninglizard.com/tinyxmldocs/index.html: "TinyXML can be compiled to use or not use STL. When using STL, TinyXML uses the std::string class, and fully supports std::istream, std::ostream, operator<<, and operator>>. Many API methods have both const char* and const std::string& forms." Of course C doesn't have std::string, so an option to use char* is still necessary (assuming it can be used from C; I'm not sure of that). Also, the home page suggests that "You may want to consider TinyXML-2". Commented Jun 5, 2015 at 15:45

2 Answers 2

7

You can't assume anything and must check the documentation for the method you are calling to know if you must free the pointer or not. Sometimes a function returning a const char * might be returning a statically allocated string:

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

Or it might be a pointer that is someone else's responsibility to free. For example, strcpy's return value is the same as the pointer you pass to it as input.

Sign up to request clarification or add additional context in comments.

Comments

5

Read the library's documentation. Both usages (pointer to an internal buffer, or pointer to a dynamically-allocated buffer) are common, and aren't distinguishable from the function prototype alone.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.