我想知道用 C 和 C++ 中返回的指向动态内存的指针来处理内存泄漏的协议。例如,strtok 返回一个 char*。据推测,返回的指针最终必须被释放/删除。我注意到参考页面甚至没有提到这一点。那是因为这只是假设吗?另外,你怎么知道是删除还是释放?是否必须进行研究以找出每个函数最初使用的语言,然后假设所有 C 程序都使用 malloc/free 而 C++ 使用 new/delete?
3 回答
strtok does NOT return a pointer to a newly allocated memory, but rather a pointer to a memory location, which has been previously allocated.
Let's assume this:
char String[1024];
strcpy(String, "This is a string");
char *Ptr = strtok(String, " ");
Ptr will not point to a newly allocated memory location, but rather to the location of String (if my counting doesn't fail me right now), with the space getting replaced by a '\0'. (
From the reference: This end of the token is automatically replaced by a null-character by the function, and the beginning of the token is returned by the function.
That also means, that if you were to print out 'String' again after strtok has done its work, it would only contain 'This', since the string is terminated after that.
As a rule of thumb, you are safe to say, that you only need to free/delete memory you've explicitly allocated yourself.
That means:
For each 'new' put a 'delete', and for each 'malloc' put a 'free' and you're good.
strtok
是一个 C 函数,它返回一个指向先前分配的内存的指针;strtok
本身不分配新内存。
如果分配了某些东西,malloc
则必须使用free
;释放它。用 new 分配的任何东西都必须与free
d 一起使用delete
。
在现代 C++ 中处理内存分配/释放的最佳方法是使用智能指针。看看std::shared_ptr
/ std::unique_ptr
,除非绝对必须,否则不要使用原始指针。
也使用std::string
andstd::vector
将删除大部分原始指针。
该strtok
函数不执行任何内存分配。它正在对您提供的字符串指针执行操作。在调用该函数时,您应该已经决定是为堆上的指针分配内存还是使用自动堆栈存储。你可以写:
char * p = "Testing - string";
char * p2 = strtok(p, "- ");
这里 p2 不必被释放/删除,因为它是在堆栈上分配的。但在这儿
char * p = "Testing - stringh";
char * p2 = malloc(strlen(p));
p2 = strtok(p, "- ");
你已经在堆上为 p2 分配了存储空间,所以在你完成它之后,它必须被释放并设置为 null:
if(p2 != NULL) {
free(p2);
p2 = NULL;
}
因此,如果您使用 new 进行堆分配,则使用 delete;如果你使用 malloc/calloc,你应该免费使用。