Delete / delete strtok_r pointer before processing a full line?

When trying to remove / free the ptr character without processing completely strtok_r , this will give me a stack trace error.

I know that you cannot free / remove strtok_r char ptr for free without completing the process of splitting whole lines of strtok_r func.

Can someone tell me how to free char ptr when its subprocess 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
source share
3 answers

Since strtok_r promotes "data" as it arrives, this means that it no longer points to the distribution address; you need to save the "freedata" pointer or the like:

 char *data, *freedata; freedata = data = new char[temp->size()+1]; // do yer stuffz here delete[] freedata; 
+4
source

The context passed to strtok_r in the third argument must be another pointer to the string you want to split. Try:

 char *context; .... pointData = strtok_r(data,":",&context); else pointData = strtok_r(NULL,":",&context); 

I do not think you need to initialize it before passing it.

+2
source

The only pointers you can ever switch to free are those received by malloc , or those obtained from functions that are specified to return a pointer to memory as if received using malloc . strtok_r does not return a pointer to the string "as if obtained using malloc ", so you can not call free on it. If you read the specification for this function, it will return a pointer to a character in your input string that has been potentially modified to compress the delimiter with a null terminator.

0
source

Source: https://habr.com/ru/post/1395795/


All Articles