1

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++;
}
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
tinku
  • 479
  • 8
  • 19

3 Answers3

4

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;
tbert
  • 2,089
  • 13
  • 14
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.

Timothy Jones
  • 21,495
  • 6
  • 60
  • 90
0

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.

R.. GitHub STOP HELPING ICE
  • 208,859
  • 35
  • 376
  • 711