谁管理类似于“strtok”的C库的内存?

huangapple go评论73阅读模式
英文:

who is managing the memory of C lib like "strtok"

问题

当我想要使用C标准库函数如strtok时,我发现它提供了一个指向堆内存的指针。我想使用C++ RAII来管理这个堆指针,但我发现无法释放它。是否有人在管理这部分内存?或者我如何确认它的生命周期?

英文:

when I want to use C lib function like strtok, I found it provided a point of heap, I want to manage this heap pointer with CPP RAII.
but I found I cannot free it, is it someone managing this part of memory? or how could I confirm its lifecycle?

谁管理类似于“strtok”的C库的内存?

答案1

得分: 6

strtok与堆无关。它不分配内存,而是返回一个指针,指向作为第一个参数传递给最后一次非空第一个参数调用的char数组内部。这个数组会因为副作用而被修改。

这个C函数具有令人困惑和容易出错的语义,它在许多目标上不可重入且不线程安全。

我建议您根本不要在C++代码中使用这个函数,特别是在需要实现RAII的情况下。

应该有C++替代方法,作为std::string类型的成员函数。

如果您想在C中编程,请考虑替代方案,如strtok_rstrsep或使用strspnstrcspn来分析字符串,这些方法不会修改源字符串,并使用strndup从堆中分配标记。

英文:

strtok does not have anything to do with the heap. It does not allocate memory, it returns a pointer inside the array of char passed as the first argument to the last call with a non null first argument. This array is modified as a side-effect.

This C function has confusing and error prone semantics, it is non reentrant and not thread safe on many targets.

I recommend you do not use this function at all, especially in c++ code where you want to implement RAII.

There should be c++ alternatives available as methods of the std::string type.

If you want to program in C, consider alternatives such as strtok_r, strsep or analyzing the string using strspn and strcspn, which to not modify the source string, and allocating the tokens from the heap with strndup.

huangapple
  • 本文由 发表于 2023年3月8日 18:19:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/75671782.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定