Free/delete strtok_r pointer before processing complete string?

狂风中的少年 提交于 2019-12-11 11:46:51

问题


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++;
}

回答1:


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:

char *data, *freedata;

freedata = data = new char[temp->size()+1];

// do yer stuffz here

delete[] freedata;



回答2:


The context passed to strtok_r in the third argument should be a different pointer to the string you want to separate. Try:

char *context;

....
pointData = strtok_r(data,":",&context);

else
pointData = strtok_r(NULL,":",&context);

I don't believe you need to initialise it before you pass it in.




回答3:


The only pointers you may ever pass to free are those obtained by malloc, or those obtained from functions which are specified to return a pointer to memory "as if" obtained by malloc. strtok_r does not return a pointer to a string "as if obtained by malloc", so you may not call free 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.



来源:https://stackoverflow.com/questions/9226653/free-delete-strtok-r-pointer-before-processing-complete-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!