处理从C中的函数返回的char数组

时间:2022-07-21 01:45:00

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

我正在使用一个名为tinyXML的库,它解析XML文件。它的许多方法都返回一个const char *。

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

读完这个问题之后:如何从C中的函数返回一个char数组

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?

我现在相信每次方法返回一个char *时,调用者(我)有责任显式释放它,因为它可能是在堆上动态分配的。我是对还是错?我能假设什么?

(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.)

(如果我写过一个库,我宁愿返回std :: string而不是char *数组,因为它们对于用户来说简单得多。)

2 个解决方案

#1


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 *的函数可能会返回一个静态分配的字符串:

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.

或者它可能是一个指针,是别人有责任释放的。例如,strcpy的返回值与作为输入传递给它的指针相同。

#2


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.

阅读图书馆的文档。两种用法(指向内部缓冲区的指针或指向动态分配缓冲区的指针)都很常见,并且不能单独与函数原型区分开来。

#1


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 *的函数可能会返回一个静态分配的字符串:

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.

或者它可能是一个指针,是别人有责任释放的。例如,strcpy的返回值与作为输入传递给它的指针相同。

#2


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.

阅读图书馆的文档。两种用法(指向内部缓冲区的指针或指向动态分配缓冲区的指针)都很常见,并且不能单独与函数原型区分开来。