在处理完整字符串之前释放/删除 strtok_r 指针?
当尝试删除/释放字符 ptr 而没有被 strtok_r 完全处理时,它给我堆栈跟踪错误。
我知道,如果不通过 strtok_r 函数完成整个字符串分离过程,就无法以常规方式释放/删除 strtok_r char ptr。
谁能告诉我如何在 strtok_r
处理时释放 char ptr?
char *data = new char[temp->size()+1];//temp is of type string
copy(temp->begin(),temp->end(),data);
data[temp->size()]='\0';
count = 0;
while(pointData != NULL)
{
if(count == 0)
pointData = strtok_r(data,":",&data);
else
pointData = strtok_r(NULL,":",&data);
if(count == 5)//some condition to free data
delete[] data;// this produces stack trace error
cout<<pointdata<<endl;
count++;
}
When trying to delete/free character ptr without being processed completely by strtok_r
, its giving me stack trace error.
I know that one cannot free/delete a strtok_r
char ptr in a regular way, without completing the whole strings separation process by strtok_r
func.
Can anyone tell me how to free a char ptr, when its under process by strtok_r
?
char *data = new char[temp->size()+1];//temp is of type string
copy(temp->begin(),temp->end(),data);
data[temp->size()]='\0';
count = 0;
while(pointData != NULL)
{
if(count == 0)
pointData = strtok_r(data,":",&data);
else
pointData = strtok_r(NULL,":",&data);
if(count == 5)//some condition to free data
delete[] data;// this produces stack trace error
cout<<pointdata<<endl;
count++;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
因为 strtok_r 正在推进“数据”,这意味着它不再指向分配的地址;你需要保留一个“freedata”指针或类似的东西:
Because strtok_r is advancing "data" as it goes, which means that it is no longer pointing at the address of the allocation; you need to keep a "freedata" pointer or the like around:
在第三个参数中传递给
strtok_r
的上下文应该是指向要分隔的字符串的不同指针。尝试:我不认为您需要在传递它之前对其进行初始化。
The context passed to
strtok_r
in the third argument should be a different pointer to the string you want to separate. Try:I don't believe you need to initialise it before you pass it in.
您可以永远传递给
free
的唯一指针是通过malloc
获得的指针,或者从指定返回内存指针的函数获得的指针“就像”由malloc
获得。strtok_r
不会返回指向字符串的指针,“就像通过malloc
获得的那样”,因此您不能对其调用free
。如果您阅读此函数的规范,它会返回一个指向输入字符串中字符的指针,该字符可能已被修改为使用空终止符破坏分隔符。The only pointers you may ever pass to
free
are those obtained bymalloc
, or those obtained from functions which are specified to return a pointer to memory "as if" obtained bymalloc
.strtok_r
does not return a pointer to a string "as if obtained bymalloc
", so you may not callfree
on it. If you read the specification for this function, it returns a pointer to character in your input string, which has been potentially modified to clobber a separator with a null terminator.