简体   繁体   中英

How to correctly manage output of strtok_r?

Let's assume I have a char buffer with data separated with char ":";

char pt[256] = "pt:ct:mac";
char *plain_text;
char *cipher_text;
char *mac;

char *next = NULL;
char *tokens = NULL;
const char sep[2] = ":";    

tokens = strtok_r(pt, sep, &next);

do
{
    if(i == 0)
    {
        int ln = strlen(tokens);
        plain_text = (char*)malloc(ln * 1);
        i++;
        continue;
    }
    if(i == 1)
    {
        int ln = strlen(tokens);
        cipher_text = (char*)malloc(ln * 1);
        i++;
        continue;
    }
    if(i == 2)
    {
        int ln = strlen(tokens);
        mac = (char*)malloc(ln * 1);
        i++;
        continue;
    }
 }
 while((tokens = strtok_r(NULL, sep, &next)) != NULL);

 free(plain_text);
 free(cipher_text);
 free(mac);

, so the question is how in the right way to deal with strtok_r output results.

Basically, the main aim is to get the results out of pt string, and put it in the dynamic containers. Since, I don't know the size of plain_text and cipher_text.

Is it the right way to program it?

Apart from that, if do see some minor mistakes or something can be written with better practices please do let me know ;) Thank you!

I would do it with array of pointers.

char pt[256] = "pt:ct:mac";

char *next = NULL;
char *token = NULL;
char *tokens[3] = {NULL};
const char sep[2] = ":";    

token = strtok_r(pt, sep, &next);

 while(token)
 {
        int ln = strlen(token);
        tokens[i]= (char*)malloc((ln * sizeof(char)) + 1);
        strcpy(tokens[i],token);
        i++;
        token = strtok_r(NULL, sep, &next);
 }

 for (int i = 0; i< 3 && tokens[i]; i++) {
   free(tokens[i]);
   tokens[i] = NULL;
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM