C/C++中最坑爷爷的垃圾函数strtok------浪费我1个小时
2016-03-28 23:29
351 查看
某次, 我调用了别人写的这样的一个函数:int Str2Vector(const string& str, vector<string> &v, const char *p);
然后,继续把str在系统中传递, 奇怪的是, 传着传着, str的值就变化了。 当时的第一分析是: 调用Str2Vector函数, str绝对不会变化, 所以一定是系统在后续传递str时出了问题。
然而, 经历较长时间追踪发现, str在后续传递过程中没有变化, 难道Str2Vector会改变str的值? 这不是在闹鬼吗? 加日志一看, 你妈, 果然是改变了。 当我进入Str2Vector中看到原函数的实现, 两年前那个strtok的坑(总结在:http://blog.csdn.net/stpeace/article/details/14047407)立即浮现在眼前, 肯定是strtok在捣鬼。 下面来看看demo代码:
taoge@localhost Desktop> g++ main.cpp
taoge@localhost Desktop> ./a.out
ab
cd
efg
h
|abcdefgh
|abcdefgh
taoge@localhost Desktop>
s和t的值居然改变了, 尤其古怪的是t的改变, 我只能呵呵哒。 说strtok最坑爹, 那是绝对不冤枉它。 strtok会改变传入的串, 所以千万要小心诡异的strtok.
由于原问题流程稍显复杂, 在这个问题上, 我浪费了1个小时, 直到看到strtok, 才立刻明白了问题所在。 坑还真多。
要和strtok函数永远地说再见了
然后,继续把str在系统中传递, 奇怪的是, 传着传着, str的值就变化了。 当时的第一分析是: 调用Str2Vector函数, str绝对不会变化, 所以一定是系统在后续传递str时出了问题。
然而, 经历较长时间追踪发现, str在后续传递过程中没有变化, 难道Str2Vector会改变str的值? 这不是在闹鬼吗? 加日志一看, 你妈, 果然是改变了。 当我进入Str2Vector中看到原函数的实现, 两年前那个strtok的坑(总结在:http://blog.csdn.net/stpeace/article/details/14047407)立即浮现在眼前, 肯定是strtok在捣鬼。 下面来看看demo代码:
#include <string> #include <iostream> #include <vector> #include <cstring> using namespace std; int Str2Vector(const string& str, vector<string> &v, const char *p) { v.clear(); char *pTmp = strtok(const_cast<char *>(str.c_str()), p); while(NULL != pTmp) { v.push_back(pTmp); pTmp = strtok(NULL, p); } return v.size(); } int main() { string s = "|ab|cd|efg|h|"; string t = s; vector<string> v; Str2Vector(s, v, "|"); for(vector<string>::iterator it = v.begin(); it != v.end(); ++it) { cout << *it << endl; } cout << s << endl; cout << t << endl; return 0; }结果居然是:
taoge@localhost Desktop> g++ main.cpp
taoge@localhost Desktop> ./a.out
ab
cd
efg
h
|abcdefgh
|abcdefgh
taoge@localhost Desktop>
s和t的值居然改变了, 尤其古怪的是t的改变, 我只能呵呵哒。 说strtok最坑爹, 那是绝对不冤枉它。 strtok会改变传入的串, 所以千万要小心诡异的strtok.
由于原问题流程稍显复杂, 在这个问题上, 我浪费了1个小时, 直到看到strtok, 才立刻明白了问题所在。 坑还真多。
要和strtok函数永远地说再见了