英文:
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?
答案1
得分: 6
strtok
与堆无关。它不分配内存,而是返回一个指针,指向作为第一个参数传递给最后一次非空第一个参数调用的char
数组内部。这个数组会因为副作用而被修改。
这个C函数具有令人困惑和容易出错的语义,它在许多目标上不可重入且不线程安全。
我建议您根本不要在C++代码中使用这个函数,特别是在需要实现RAII的情况下。
应该有C++替代方法,作为std::string
类型的成员函数。
如果您想在C中编程,请考虑替代方案,如strtok_r
、strsep
或使用strspn
和strcspn
来分析字符串,这些方法不会修改源字符串,并使用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
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论