0

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!

mhibert
  • 67
  • 6
  • 2
    Just FYI, I'm assuming your test data is exemplary, but eventually you're acquiring data from someplace besides a pre-defined value. One "right" way is to actually test the *first* invoke and not ignore the potential error. In case you hadn't thought of it, `strtok_r` can return NULL even on the *first* call, which you ignore. It would be simple enough address, and you really should. Just saying. – WhozCraig Feb 03 '20 at 09:56

1 Answers1

0

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;
 }
kiran Biradar
  • 12,700
  • 3
  • 19
  • 44
  • I like your answer, as far as I am aware "strcpy" function is considered as unsafe. As an example, https://stackoverflow.com/questions/23317646/why-is-strcpy-unsafe-in-c. In more depth understanding why it is unsafe you can refer to Microsoft. – mhibert Feb 03 '20 at 10:10
  • (char*)malloc((ln * sizeof(char)) + 1); in this line. Why you are adding + 1? Let's say we have ln of 50. Then, 50 * 1 + 1. 51? – mhibert Feb 03 '20 at 10:13
  • `pluss 1` to hold `null` char. – kiran Biradar Feb 03 '20 at 10:36